path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
---|---|---|
node_modules/react-select/examples/src/components/CustomRender.js | together-web-pj/together-web-pj | import React from 'react';
import createClass from 'create-react-class';
import PropTypes from 'prop-types';
import Select from 'react-select';
import Highlighter from 'react-highlight-words';
var DisabledUpsellOptions = createClass({
displayName: 'DisabledUpsellOptions',
propTypes: {
label: PropTypes.string,
},
getInitialState () {
return {};
},
setValue (value) {
this.setState({ value });
if (value) {
console.log('Support level selected:', value.label);
}
},
renderLink: function() {
return <a style={{ marginLeft: 5 }} href="/upgrade" target="_blank">Upgrade here!</a>;
},
renderOption: function(option) {
return (
<Highlighter
searchWords={[this._inputValue]}
textToHighlight={option.label}
/>
);
},
renderValue: function(option) {
return <strong style={{ color: option.color }}>{option.label}</strong>;
},
render: function() {
var options = [
{ label: 'Basic customer support', value: 'basic', color: '#E31864' },
{ label: 'Premium customer support', value: 'premium', color: '#6216A3' },
{ label: 'Pro customer support', value: 'pro', disabled: true, link: this.renderLink() },
];
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select
onInputChange={(inputValue) => this._inputValue = inputValue}
options={options}
optionRenderer={this.renderOption}
onChange={this.setValue}
value={this.state.value}
valueRenderer={this.renderValue}
/>
<div className="hint">This demonstates custom render methods and links in disabled options</div>
</div>
);
}
});
module.exports = DisabledUpsellOptions;
|
modules/angular2/src/core/compiler/element_injector.js | boxman0617/angular | import {isPresent, isBlank, Type, int, BaseException, stringify} from 'angular2/src/facade/lang';
import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {Math} from 'angular2/src/facade/math';
import {List, ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {Injector, Key, Dependency, bind, Binding, ResolvedBinding, NoBindingError,
AbstractBindingError, CyclicDependencyError} from 'angular2/di';
import {Parent, Ancestor} from 'angular2/src/core/annotations_impl/visibility';
import {Attribute, Query} from 'angular2/src/core/annotations_impl/di';
import * as viewModule from './view';
import * as avmModule from './view_manager';
import {ViewContainerRef} from './view_container_ref';
import {ElementRef} from './element_ref';
import {ProtoViewRef, ViewRef} from './view_ref';
import {Directive, Component, onChange, onDestroy, onAllChangesDone} from 'angular2/src/core/annotations_impl/annotations';
import {ChangeDetector, ChangeDetectorRef} from 'angular2/change_detection';
import {QueryList} from './query_list';
import {reflector} from 'angular2/src/reflection/reflection';
var _MAX_DIRECTIVE_CONSTRUCTION_COUNTER = 10;
var MAX_DEPTH = Math.pow(2, 30) - 1;
var _undefined = new Object();
var _staticKeys;
class StaticKeys {
viewManagerId:number;
protoViewId:number;
viewContainerId:number;
changeDetectorRefId:number;
elementRefId:number;
constructor() {
//TODO: vsavkin Key.annotate(Key.get(AppView), 'static')
this.viewManagerId = Key.get(avmModule.AppViewManager).id;
this.protoViewId = Key.get(ProtoViewRef).id;
this.viewContainerId = Key.get(ViewContainerRef).id;
this.changeDetectorRefId = Key.get(ChangeDetectorRef).id;
this.elementRefId = Key.get(ElementRef).id;
}
static instance():StaticKeys {
if (isBlank(_staticKeys)) _staticKeys = new StaticKeys();
return _staticKeys;
}
}
export class TreeNode {
_parent:TreeNode;
_head:TreeNode;
_tail:TreeNode;
_next:TreeNode;
constructor(parent:TreeNode) {
this._head = null;
this._tail = null;
this._next = null;
if (isPresent(parent)) parent.addChild(this);
}
_assertConsistency():void {
this._assertHeadBeforeTail();
this._assertTailReachable();
this._assertPresentInParentList();
}
_assertHeadBeforeTail():void {
if (isBlank(this._tail) && isPresent(this._head)) throw new BaseException('null tail but non-null head');
}
_assertTailReachable():void {
if (isBlank(this._tail)) return;
if (isPresent(this._tail._next)) throw new BaseException('node after tail');
var p = this._head;
while (isPresent(p) && p != this._tail) p = p._next;
if (isBlank(p) && isPresent(this._tail)) throw new BaseException('tail not reachable.')
}
_assertPresentInParentList():void {
var p = this._parent;
if (isBlank(p)) {
return;
}
var cur = p._head;
while (isPresent(cur) && cur != this) cur = cur._next;
if (isBlank(cur)) throw new BaseException('node not reachable through parent.')
}
/**
* Adds a child to the parent node. The child MUST NOT be a part of a tree.
*/
addChild(child:TreeNode):void {
if (isPresent(this._tail)) {
this._tail._next = child;
this._tail = child;
} else {
this._tail = this._head = child;
}
child._next = null;
child._parent = this;
this._assertConsistency();
}
/**
* Adds a child to the parent node after a given sibling.
* The child MUST NOT be a part of a tree and the sibling must be present.
*/
addChildAfter(child:TreeNode, prevSibling:TreeNode):void {
this._assertConsistency();
if (isBlank(prevSibling)) {
var prevHead = this._head;
this._head = child;
child._next = prevHead;
if (isBlank(this._tail)) this._tail = child;
} else if (isBlank(prevSibling._next)) {
this.addChild(child);
return;
} else {
prevSibling._assertPresentInParentList();
child._next = prevSibling._next;
prevSibling._next = child;
}
child._parent = this;
this._assertConsistency();
}
/**
* Detaches a node from the parent's tree.
*/
remove():void {
this._assertConsistency();
if (isBlank(this.parent)) return;
var nextSibling = this._next;
var prevSibling = this._findPrev();
if (isBlank(prevSibling)) {
this.parent._head = this._next;
} else {
prevSibling._next = this._next;
}
if (isBlank(nextSibling)) {
this._parent._tail = prevSibling;
}
this._parent._assertConsistency();
this._parent = null;
this._next = null;
this._assertConsistency();
}
/**
* Finds a previous sibling or returns null if first child.
* Assumes the node has a parent.
* TODO(rado): replace with DoublyLinkedList to avoid O(n) here.
*/
_findPrev() {
var node = this.parent._head;
if (node == this) return null;
while (node._next !== this) node = node._next;
return node;
}
get parent() {
return this._parent;
}
// TODO(rado): replace with a function call, does too much work for a getter.
get children() {
var res = [];
var child = this._head;
while (child != null) {
ListWrapper.push(res, child);
child = child._next;
}
return res;
}
}
export class DirectiveDependency extends Dependency {
depth:int;
attributeName:string;
queryDirective;
constructor(key:Key, asPromise:boolean, lazy:boolean, optional:boolean, properties:List,
depth:int, attributeName:string, queryDirective) {
super(key, asPromise, lazy, optional, properties);
this.depth = depth;
this.attributeName = attributeName;
this.queryDirective = queryDirective;
this._verify();
}
_verify():void {
var count = 0;
if (isPresent(this.queryDirective)) count++;
if (isPresent(this.attributeName)) count++;
if (count > 1) throw new BaseException(
'A directive injectable can contain only one of the following @Attribute or @Query.');
}
static createFrom(d:Dependency):Dependency {
return new DirectiveDependency(d.key, d.asPromise, d.lazy, d.optional,
d.properties, DirectiveDependency._depth(d.properties),
DirectiveDependency._attributeName(d.properties),
DirectiveDependency._query(d.properties)
);
}
static _depth(properties):int {
if (properties.length == 0) return 0;
if (ListWrapper.any(properties, p => p instanceof Parent)) return 1;
if (ListWrapper.any(properties, p => p instanceof Ancestor)) return MAX_DEPTH;
return 0;
}
static _attributeName(properties):string {
var p = ListWrapper.find(properties, (p) => p instanceof Attribute);
return isPresent(p) ? p.attributeName : null;
}
static _query(properties) {
var p = ListWrapper.find(properties, (p) => p instanceof Query);
return isPresent(p) ? p.directive : null;
}
}
export class DirectiveBinding extends ResolvedBinding {
callOnDestroy:boolean;
callOnChange:boolean;
callOnAllChangesDone:boolean;
annotation:Directive;
resolvedInjectables:List<ResolvedBinding>;
constructor(key:Key, factory:Function, dependencies:List, providedAsPromise:boolean, annotation:Directive) {
super(key, factory, dependencies, providedAsPromise);
this.callOnDestroy = isPresent(annotation) && annotation.hasLifecycleHook(onDestroy);
this.callOnChange = isPresent(annotation) && annotation.hasLifecycleHook(onChange);
this.callOnAllChangesDone = isPresent(annotation) && annotation.hasLifecycleHook(onAllChangesDone);
this.annotation = annotation;
if (annotation instanceof Component && isPresent(annotation.injectables)) {
this.resolvedInjectables = Injector.resolve(annotation.injectables);
}
}
get displayName() {
return this.key.displayName;
}
get eventEmitters():List<string> {
return isPresent(this.annotation) && isPresent(this.annotation.events) ? this.annotation.events : [];
}
get hostActions() { //StringMap
return isPresent(this.annotation) && isPresent(this.annotation.hostActions) ? this.annotation.hostActions : {};
}
get changeDetection() {
if (this.annotation instanceof Component) {
var c:Component = this.annotation;
return c.changeDetection;
} else {
return null;
}
}
static createFromBinding(b:Binding, annotation:Directive):DirectiveBinding {
var rb = b.resolve();
var deps = ListWrapper.map(rb.dependencies, DirectiveDependency.createFrom);
return new DirectiveBinding(rb.key, rb.factory, deps, rb.providedAsPromise, annotation);
}
static createFromType(type:Type, annotation:Directive):DirectiveBinding {
var binding = new Binding(type, {toClass: type});
return DirectiveBinding.createFromBinding(binding, annotation);
}
}
// TODO(rado): benchmark and consider rolling in as ElementInjector fields.
export class PreBuiltObjects {
viewManager:avmModule.AppViewManager;
protoView:viewModule.AppProtoView;
view:viewModule.AppView;
constructor(viewManager:avmModule.AppViewManager, view:viewModule.AppView, protoView:viewModule.AppProtoView) {
this.viewManager = viewManager;
this.view = view;
this.protoView = protoView;
}
}
class EventEmitterAccessor {
eventName:string;
getter:Function;
constructor(eventName:string, getter:Function) {
this.eventName = eventName;
this.getter = getter;
}
subscribe(view:viewModule.AppView, boundElementIndex:number, directive:Object) {
var eventEmitter = this.getter(directive);
return ObservableWrapper.subscribe(eventEmitter,
eventObj => view.triggerEventHandlers(this.eventName, eventObj, boundElementIndex));
}
}
class HostActionAccessor {
actionExpression:string;
getter:Function;
constructor(actionExpression:string, getter:Function) {
this.actionExpression = actionExpression;
this.getter = getter;
}
subscribe(view:viewModule.AppView, boundElementIndex:number, directive:Object) {
var eventEmitter = this.getter(directive);
return ObservableWrapper.subscribe(eventEmitter,
actionObj => view.callAction(boundElementIndex, this.actionExpression, actionObj));
}
}
/**
Difference between di.Injector and ElementInjector
di.Injector:
- imperative based (can create child injectors imperativly)
- Lazy loading of code
- Component/App Level services which are usually not DOM Related.
ElementInjector:
- ProtoBased (Injector structure fixed at compile time)
- understands @Ancestor, @Parent, @Child, @Descendent
- Fast
- Query mechanism for children
- 1:1 to DOM structure.
PERF BENCHMARK: http://www.williambrownstreet.net/blog/2014/04/faster-angularjs-rendering-angularjs-and-reactjs/
*/
export class ProtoElementInjector {
_binding0:DirectiveBinding;
_binding1:DirectiveBinding;
_binding2:DirectiveBinding;
_binding3:DirectiveBinding;
_binding4:DirectiveBinding;
_binding5:DirectiveBinding;
_binding6:DirectiveBinding;
_binding7:DirectiveBinding;
_binding8:DirectiveBinding;
_binding9:DirectiveBinding;
_binding0IsComponent:boolean;
_keyId0:int;
_keyId1:int;
_keyId2:int;
_keyId3:int;
_keyId4:int;
_keyId5:int;
_keyId6:int;
_keyId7:int;
_keyId8:int;
_keyId9:int;
parent:ProtoElementInjector;
index:int;
view:viewModule.AppView;
distanceToParent:number;
attributes:Map;
eventEmitterAccessors:List<List<EventEmitterAccessor>>;
hostActionAccessors:List<List<HostActionAccessor>>;
numberOfDirectives:number;
/** Whether the element is exported as $implicit. */
exportElement:boolean;
/** Whether the component instance is exported as $implicit. */
exportComponent:boolean;
/** The variable name that will be set to $implicit for the element. */
exportImplicitName:string;
constructor(parent:ProtoElementInjector, index:int, bindings:List, firstBindingIsComponent:boolean = false, distanceToParent:number = 0) {
this.parent = parent;
this.index = index;
this.distanceToParent = distanceToParent;
this.exportComponent = false;
this.exportElement = false;
this._binding0IsComponent = firstBindingIsComponent;
this._binding0 = null; this._keyId0 = null;
this._binding1 = null; this._keyId1 = null;
this._binding2 = null; this._keyId2 = null;
this._binding3 = null; this._keyId3 = null;
this._binding4 = null; this._keyId4 = null;
this._binding5 = null; this._keyId5 = null;
this._binding6 = null; this._keyId6 = null;
this._binding7 = null; this._keyId7 = null;
this._binding8 = null; this._keyId8 = null;
this._binding9 = null; this._keyId9 = null;
this.numberOfDirectives = bindings.length;
var length = bindings.length;
this.eventEmitterAccessors = ListWrapper.createFixedSize(length);
this.hostActionAccessors = ListWrapper.createFixedSize(length);
if (length > 0) {
this._binding0 = this._createBinding(bindings[0]);
this._keyId0 = this._binding0.key.id;
this.eventEmitterAccessors[0] = this._createEventEmitterAccessors(this._binding0);
this.hostActionAccessors[0] = this._createHostActionAccessors(this._binding0);
}
if (length > 1) {
this._binding1 = this._createBinding(bindings[1]);
this._keyId1 = this._binding1.key.id;
this.eventEmitterAccessors[1] = this._createEventEmitterAccessors(this._binding1);
this.hostActionAccessors[1] = this._createHostActionAccessors(this._binding1);
}
if (length > 2) {
this._binding2 = this._createBinding(bindings[2]);
this._keyId2 = this._binding2.key.id;
this.eventEmitterAccessors[2] = this._createEventEmitterAccessors(this._binding2);
this.hostActionAccessors[2] = this._createHostActionAccessors(this._binding2);
}
if (length > 3) {
this._binding3 = this._createBinding(bindings[3]);
this._keyId3 = this._binding3.key.id;
this.eventEmitterAccessors[3] = this._createEventEmitterAccessors(this._binding3);
this.hostActionAccessors[3] = this._createHostActionAccessors(this._binding3);
}
if (length > 4) {
this._binding4 = this._createBinding(bindings[4]);
this._keyId4 = this._binding4.key.id;
this.eventEmitterAccessors[4] = this._createEventEmitterAccessors(this._binding4);
this.hostActionAccessors[4] = this._createHostActionAccessors(this._binding4);
}
if (length > 5) {
this._binding5 = this._createBinding(bindings[5]);
this._keyId5 = this._binding5.key.id;
this.eventEmitterAccessors[5] = this._createEventEmitterAccessors(this._binding5);
this.hostActionAccessors[5] = this._createHostActionAccessors(this._binding5);
}
if (length > 6) {
this._binding6 = this._createBinding(bindings[6]);
this._keyId6 = this._binding6.key.id;
this.eventEmitterAccessors[6] = this._createEventEmitterAccessors(this._binding6);
this.hostActionAccessors[6] = this._createHostActionAccessors(this._binding6);
}
if (length > 7) {
this._binding7 = this._createBinding(bindings[7]);
this._keyId7 = this._binding7.key.id;
this.eventEmitterAccessors[7] = this._createEventEmitterAccessors(this._binding7);
this.hostActionAccessors[7] = this._createHostActionAccessors(this._binding7);
}
if (length > 8) {
this._binding8 = this._createBinding(bindings[8]);
this._keyId8 = this._binding8.key.id;
this.eventEmitterAccessors[8] = this._createEventEmitterAccessors(this._binding8);
this.hostActionAccessors[8] = this._createHostActionAccessors(this._binding8);
}
if (length > 9) {
this._binding9 = this._createBinding(bindings[9]);
this._keyId9 = this._binding9.key.id;
this.eventEmitterAccessors[9] = this._createEventEmitterAccessors(this._binding9);
this.hostActionAccessors[9] = this._createHostActionAccessors(this._binding9);
}
if (length > 10) {
throw 'Maximum number of directives per element has been reached.';
}
}
_createEventEmitterAccessors(b:DirectiveBinding) {
return ListWrapper.map(b.eventEmitters, eventName =>
new EventEmitterAccessor(eventName, reflector.getter(eventName))
);
}
_createHostActionAccessors(b:DirectiveBinding) {
var res = [];
StringMapWrapper.forEach(b.hostActions, (actionExpression, actionName) => {
ListWrapper.push(res, new HostActionAccessor(actionExpression, reflector.getter(actionName)))
});
return res;
}
instantiate(parent:ElementInjector):ElementInjector {
return new ElementInjector(this, parent);
}
directParent(): ProtoElementInjector {
return this.distanceToParent < 2 ? this.parent : null;
}
_createBinding(bindingOrType) {
if (bindingOrType instanceof DirectiveBinding) {
return bindingOrType;
} else {
var b = bind(bindingOrType).toClass(bindingOrType);
return DirectiveBinding.createFromBinding(b, null);
}
}
get hasBindings():boolean {
return isPresent(this._binding0);
}
getDirectiveBindingAtIndex(index:int) {
if (index == 0) return this._binding0;
if (index == 1) return this._binding1;
if (index == 2) return this._binding2;
if (index == 3) return this._binding3;
if (index == 4) return this._binding4;
if (index == 5) return this._binding5;
if (index == 6) return this._binding6;
if (index == 7) return this._binding7;
if (index == 8) return this._binding8;
if (index == 9) return this._binding9;
throw new OutOfBoundsAccess(index);
}
}
export class ElementInjector extends TreeNode {
_proto:ProtoElementInjector;
_lightDomAppInjector:Injector;
_shadowDomAppInjector:Injector;
_host:ElementInjector;
// If this element injector has a component, the component instance will be stored in _obj0
_obj0:any;
_obj1:any;
_obj2:any;
_obj3:any;
_obj4:any;
_obj5:any;
_obj6:any;
_obj7:any;
_obj8:any;
_obj9:any;
_preBuiltObjects;
_constructionCounter;
_dynamicallyCreatedComponent:any;
_dynamicallyCreatedComponentBinding:DirectiveBinding;
// Queries are added during construction or linking with a new parent.
// They are never removed.
_query0: QueryRef;
_query1: QueryRef;
_query2: QueryRef;
constructor(proto:ProtoElementInjector, parent:ElementInjector) {
super(parent);
this._proto = proto;
//we cannot call clearDirectives because fields won't be detected
this._preBuiltObjects = null;
this._lightDomAppInjector = null;
this._shadowDomAppInjector = null;
this._obj0 = null;
this._obj1 = null;
this._obj2 = null;
this._obj3 = null;
this._obj4 = null;
this._obj5 = null;
this._obj6 = null;
this._obj7 = null;
this._obj8 = null;
this._obj9 = null;
this._constructionCounter = 0;
this._inheritQueries(parent);
this._buildQueries();
}
clearDirectives() {
this._host = null;
this._preBuiltObjects = null;
this._lightDomAppInjector = null;
this._shadowDomAppInjector = null;
var p = this._proto;
if (isPresent(p._binding0) && p._binding0.callOnDestroy) {this._obj0.onDestroy();}
if (isPresent(p._binding1) && p._binding1.callOnDestroy) {this._obj1.onDestroy();}
if (isPresent(p._binding2) && p._binding2.callOnDestroy) {this._obj2.onDestroy();}
if (isPresent(p._binding3) && p._binding3.callOnDestroy) {this._obj3.onDestroy();}
if (isPresent(p._binding4) && p._binding4.callOnDestroy) {this._obj4.onDestroy();}
if (isPresent(p._binding5) && p._binding5.callOnDestroy) {this._obj5.onDestroy();}
if (isPresent(p._binding6) && p._binding6.callOnDestroy) {this._obj6.onDestroy();}
if (isPresent(p._binding7) && p._binding7.callOnDestroy) {this._obj7.onDestroy();}
if (isPresent(p._binding8) && p._binding8.callOnDestroy) {this._obj8.onDestroy();}
if (isPresent(p._binding9) && p._binding9.callOnDestroy) {this._obj9.onDestroy();}
if (isPresent(this._dynamicallyCreatedComponentBinding) && this._dynamicallyCreatedComponentBinding.callOnDestroy) {
this._dynamicallyCreatedComponent.onDestroy();
}
this._obj0 = null;
this._obj1 = null;
this._obj2 = null;
this._obj3 = null;
this._obj4 = null;
this._obj5 = null;
this._obj6 = null;
this._obj7 = null;
this._obj8 = null;
this._obj9 = null;
this._dynamicallyCreatedComponent = null;
this._dynamicallyCreatedComponentBinding = null;
this._constructionCounter = 0;
}
instantiateDirectives(
lightDomAppInjector:Injector,
host:ElementInjector,
preBuiltObjects:PreBuiltObjects) {
var shadowDomAppInjector = null;
if (this._proto._binding0IsComponent) {
shadowDomAppInjector = this._createShadowDomAppInjector(this._proto._binding0, lightDomAppInjector);
}
this._host = host;
this._checkShadowDomAppInjector(shadowDomAppInjector);
this._preBuiltObjects = preBuiltObjects;
this._lightDomAppInjector = lightDomAppInjector;
this._shadowDomAppInjector = shadowDomAppInjector;
var p = this._proto;
if (isPresent(p._keyId0)) this._getDirectiveByKeyId(p._keyId0);
if (isPresent(shadowDomAppInjector)) {
var componentAnnotation:Component = this._proto._binding0.annotation;
var publishAs = componentAnnotation.publishAs;
if (isPresent(publishAs) && publishAs.length > 0) {
// If there's a component directive on this element injector, then
// 0-th key must contain the directive itself.
// TODO(yjbanov): need to make injector creation faster:
// - remove flattening of bindings array
// - precalc token key
this._shadowDomAppInjector = shadowDomAppInjector.resolveAndCreateChild(
ListWrapper.map(publishAs, (token) => {
return bind(token).toValue(this.getComponent());
}));
}
}
if (isPresent(p._keyId1)) this._getDirectiveByKeyId(p._keyId1);
if (isPresent(p._keyId2)) this._getDirectiveByKeyId(p._keyId2);
if (isPresent(p._keyId3)) this._getDirectiveByKeyId(p._keyId3);
if (isPresent(p._keyId4)) this._getDirectiveByKeyId(p._keyId4);
if (isPresent(p._keyId5)) this._getDirectiveByKeyId(p._keyId5);
if (isPresent(p._keyId6)) this._getDirectiveByKeyId(p._keyId6);
if (isPresent(p._keyId7)) this._getDirectiveByKeyId(p._keyId7);
if (isPresent(p._keyId8)) this._getDirectiveByKeyId(p._keyId8);
if (isPresent(p._keyId9)) this._getDirectiveByKeyId(p._keyId9);
}
_createShadowDomAppInjector(componentDirective:DirectiveBinding, appInjector:Injector) {
var shadowDomAppInjector = null;
// shadowDomAppInjector
var injectables = componentDirective.resolvedInjectables;
if (isPresent(injectables)) {
shadowDomAppInjector = appInjector.createChildFromResolved(injectables);
} else {
shadowDomAppInjector = appInjector;
}
return shadowDomAppInjector;
}
dynamicallyCreateComponent(componentDirective:DirectiveBinding, parentInjector:Injector) {
this._shadowDomAppInjector = this._createShadowDomAppInjector(componentDirective, parentInjector);
this._dynamicallyCreatedComponentBinding = componentDirective;
this._dynamicallyCreatedComponent = this._new(this._dynamicallyCreatedComponentBinding);
return this._dynamicallyCreatedComponent;
}
_checkShadowDomAppInjector(shadowDomAppInjector:Injector) {
if (this._proto._binding0IsComponent && isBlank(shadowDomAppInjector)) {
throw new BaseException('A shadowDomAppInjector is required as this ElementInjector contains a component');
} else if (!this._proto._binding0IsComponent && isPresent(shadowDomAppInjector)) {
throw new BaseException('No shadowDomAppInjector allowed as there is not component stored in this ElementInjector');
}
}
get(token) {
if (this._isDynamicallyLoadedComponent(token)) {
return this._dynamicallyCreatedComponent;
}
return this._getByKey(Key.get(token), 0, false, null);
}
_isDynamicallyLoadedComponent(token) {
return isPresent(this._dynamicallyCreatedComponentBinding) &&
Key.get(token) === this._dynamicallyCreatedComponentBinding.key;
}
hasDirective(type:Type):boolean {
return this._getDirectiveByKeyId(Key.get(type).id) !== _undefined;
}
getEventEmitterAccessors() {
return this._proto.eventEmitterAccessors;
}
getHostActionAccessors() {
return this._proto.hostActionAccessors;
}
getComponent() {
if (this._proto._binding0IsComponent) {
return this._obj0;
} else {
throw new BaseException('There is no component stored in this ElementInjector');
}
}
getElementRef() {
return new ElementRef(new ViewRef(this._preBuiltObjects.view), this._proto.index);
}
getViewContainerRef() {
return new ViewContainerRef(this._preBuiltObjects.viewManager, this.getElementRef());
}
getDynamicallyLoadedComponent() {
return this._dynamicallyCreatedComponent;
}
directParent(): ElementInjector {
return this._proto.distanceToParent < 2 ? this.parent : null;
}
_isComponentKey(key:Key) {
return this._proto._binding0IsComponent && key.id === this._proto._keyId0;
}
_isDynamicallyLoadedComponentKey(key:Key) {
return isPresent(this._dynamicallyCreatedComponentBinding) && key.id ===
this._dynamicallyCreatedComponentBinding.key.id;
}
_new(binding:ResolvedBinding) {
if (this._constructionCounter++ > _MAX_DIRECTIVE_CONSTRUCTION_COUNTER) {
throw new CyclicDependencyError(binding.key);
}
var factory = binding.factory;
var deps = binding.dependencies;
var length = deps.length;
var d0,d1,d2,d3,d4,d5,d6,d7,d8,d9;
try {
d0 = length > 0 ? this._getByDependency(deps[0], binding.key) : null;
d1 = length > 1 ? this._getByDependency(deps[1], binding.key) : null;
d2 = length > 2 ? this._getByDependency(deps[2], binding.key) : null;
d3 = length > 3 ? this._getByDependency(deps[3], binding.key) : null;
d4 = length > 4 ? this._getByDependency(deps[4], binding.key) : null;
d5 = length > 5 ? this._getByDependency(deps[5], binding.key) : null;
d6 = length > 6 ? this._getByDependency(deps[6], binding.key) : null;
d7 = length > 7 ? this._getByDependency(deps[7], binding.key) : null;
d8 = length > 8 ? this._getByDependency(deps[8], binding.key) : null;
d9 = length > 9 ? this._getByDependency(deps[9], binding.key) : null;
} catch(e) {
if (e instanceof AbstractBindingError) e.addKey(binding.key);
throw e;
}
var obj;
switch(length) {
case 0: obj = factory(); break;
case 1: obj = factory(d0); break;
case 2: obj = factory(d0, d1); break;
case 3: obj = factory(d0, d1, d2); break;
case 4: obj = factory(d0, d1, d2, d3); break;
case 5: obj = factory(d0, d1, d2, d3, d4); break;
case 6: obj = factory(d0, d1, d2, d3, d4, d5); break;
case 7: obj = factory(d0, d1, d2, d3, d4, d5, d6); break;
case 8: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7); break;
case 9: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8); break;
case 10: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9); break;
default: throw `Directive ${binding.key.token} can only have up to 10 dependencies.`;
}
this._addToQueries(obj, binding.key.token);
return obj;
}
_getByDependency(dep:DirectiveDependency, requestor:Key) {
if (isPresent(dep.attributeName)) return this._buildAttribute(dep);
if (isPresent(dep.queryDirective)) return this._findQuery(dep.queryDirective).list;
if (dep.key.id === StaticKeys.instance().changeDetectorRefId) {
var componentView = this._preBuiltObjects.view.componentChildViews[this._proto.index];
return componentView.changeDetector.ref;
}
if (dep.key.id === StaticKeys.instance().elementRefId) {
return this.getElementRef();
}
if (dep.key.id === StaticKeys.instance().viewContainerId) {
return this.getViewContainerRef();
}
if (dep.key.id === StaticKeys.instance().protoViewId) {
if (isBlank(this._preBuiltObjects.protoView)) {
throw new NoBindingError(dep.key);
}
return new ProtoViewRef(this._preBuiltObjects.protoView);
}
return this._getByKey(dep.key, dep.depth, dep.optional, requestor);
}
_buildAttribute(dep): string {
var attributes = this._proto.attributes;
if (isPresent(attributes) && MapWrapper.contains(attributes, dep.attributeName)) {
return MapWrapper.get(attributes, dep.attributeName);
} else {
return null;
}
}
_buildQueriesForDeps(deps: List<DirectiveDependency>) {
for (var i = 0; i < deps.length; i++) {
var dep = deps[i];
if (isPresent(dep.queryDirective)) {
this._createQueryRef(dep.queryDirective);
}
}
}
_createQueryRef(directive) {
var queryList = new QueryList();
if (isBlank(this._query0)) {this._query0 = new QueryRef(directive, queryList, this);}
else if (isBlank(this._query1)) {this._query1 = new QueryRef(directive, queryList, this);}
else if (isBlank(this._query2)) {this._query2 = new QueryRef(directive, queryList, this);}
else throw new QueryError();
}
_addToQueries(obj, token) {
if (isPresent(this._query0) && (this._query0.directive === token)) {this._query0.list.add(obj);}
if (isPresent(this._query1) && (this._query1.directive === token)) {this._query1.list.add(obj);}
if (isPresent(this._query2) && (this._query2.directive === token)) {this._query2.list.add(obj);}
}
// TODO(rado): unify with _addParentQueries.
_inheritQueries(parent: ElementInjector) {
if (isBlank(parent)) return;
if (isPresent(parent._query0)) {this._query0 = parent._query0;}
if (isPresent(parent._query1)) {this._query1 = parent._query1;}
if (isPresent(parent._query2)) {this._query2 = parent._query2;}
}
_buildQueries() {
if (isBlank(this._proto)) return;
var p = this._proto;
if (isPresent(p._binding0)) {this._buildQueriesForDeps(p._binding0.dependencies);}
if (isPresent(p._binding1)) {this._buildQueriesForDeps(p._binding1.dependencies);}
if (isPresent(p._binding2)) {this._buildQueriesForDeps(p._binding2.dependencies);}
if (isPresent(p._binding3)) {this._buildQueriesForDeps(p._binding3.dependencies);}
if (isPresent(p._binding4)) {this._buildQueriesForDeps(p._binding4.dependencies);}
if (isPresent(p._binding5)) {this._buildQueriesForDeps(p._binding5.dependencies);}
if (isPresent(p._binding6)) {this._buildQueriesForDeps(p._binding6.dependencies);}
if (isPresent(p._binding7)) {this._buildQueriesForDeps(p._binding7.dependencies);}
if (isPresent(p._binding8)) {this._buildQueriesForDeps(p._binding8.dependencies);}
if (isPresent(p._binding9)) {this._buildQueriesForDeps(p._binding9.dependencies);}
}
_findQuery(token) {
if (isPresent(this._query0) && this._query0.directive === token) {return this._query0;}
if (isPresent(this._query1) && this._query1.directive === token) {return this._query1;}
if (isPresent(this._query2) && this._query2.directive === token) {return this._query2;}
throw new BaseException(`Cannot find query for directive ${token}.`);
}
link(parent: ElementInjector) {
parent.addChild(this);
this._addParentQueries();
}
linkAfter(parent: ElementInjector, prevSibling: ElementInjector) {
parent.addChildAfter(this, prevSibling);
this._addParentQueries();
}
_addParentQueries() {
if (isPresent(this.parent._query0)) {this._addQueryToTree(this.parent._query0); this.parent._query0.update();}
if (isPresent(this.parent._query1)) {this._addQueryToTree(this.parent._query1); this.parent._query1.update();}
if (isPresent(this.parent._query2)) {this._addQueryToTree(this.parent._query2); this.parent._query2.update();}
}
unlink() {
var queriesToUpDate = [];
if (isPresent(this.parent._query0)) {this._pruneQueryFromTree(this.parent._query0); ListWrapper.push(queriesToUpDate, this.parent._query0);}
if (isPresent(this.parent._query1)) {this._pruneQueryFromTree(this.parent._query1); ListWrapper.push(queriesToUpDate, this.parent._query1);}
if (isPresent(this.parent._query2)) {this._pruneQueryFromTree(this.parent._query2); ListWrapper.push(queriesToUpDate, this.parent._query2);}
this.remove();
ListWrapper.forEach(queriesToUpDate, (q) => q.update());
}
_pruneQueryFromTree(query: QueryRef) {
this._removeQueryRef(query);
var child = this._head;
while (isPresent(child)) {
child._pruneQueryFromTree(query);
child = child._next;
}
}
_addQueryToTree(query: QueryRef) {
this._assignQueryRef(query);
var child = this._head;
while (isPresent(child)) {
child._addQueryToTree(query);
child = child._next;
}
}
_assignQueryRef(query: QueryRef) {
if (isBlank(this._query0)) {this._query0 = query; return;}
else if (isBlank(this._query1)) {this._query1 = query; return;}
else if (isBlank(this._query2)) {this._query2 = query; return;}
throw new QueryError();
}
_removeQueryRef(query: QueryRef) {
if (this._query0 == query) this._query0 = null;
if (this._query1 == query) this._query1 = null;
if (this._query2 == query) this._query2 = null;
}
_getByKey(key:Key, depth:number, optional:boolean, requestor:Key) {
var ei = this;
if (! this._shouldIncludeSelf(depth)) {
depth -= ei._proto.distanceToParent;
ei = ei._parent;
}
while (ei != null && depth >= 0) {
var preBuiltObj = ei._getPreBuiltObjectByKeyId(key.id);
if (preBuiltObj !== _undefined) return preBuiltObj;
var dir = ei._getDirectiveByKeyId(key.id);
if (dir !== _undefined) return dir;
depth -= ei._proto.distanceToParent;
ei = ei._parent;
}
if (isPresent(this._host) && this._host._isComponentKey(key)) {
return this._host.getComponent();
} else if (isPresent(this._host) && this._host._isDynamicallyLoadedComponentKey(key)) {
return this._host.getDynamicallyLoadedComponent();
} else if (optional) {
return this._appInjector(requestor).getOptional(key);
} else {
return this._appInjector(requestor).get(key);
}
}
_appInjector(requestor:Key) {
if (isPresent(requestor) && (this._isComponentKey(requestor) || this._isDynamicallyLoadedComponentKey(requestor))) {
return this._shadowDomAppInjector;
} else {
return this._lightDomAppInjector;
}
}
_shouldIncludeSelf(depth:int) {
return depth === 0;
}
_getPreBuiltObjectByKeyId(keyId:int) {
var staticKeys = StaticKeys.instance();
if (keyId === staticKeys.viewManagerId) return this._preBuiltObjects.viewManager;
//TODO add other objects as needed
return _undefined;
}
_getDirectiveByKeyId(keyId:int) {
var p = this._proto;
if (p._keyId0 === keyId) {if (isBlank(this._obj0)){this._obj0 = this._new(p._binding0);} return this._obj0;}
if (p._keyId1 === keyId) {if (isBlank(this._obj1)){this._obj1 = this._new(p._binding1);} return this._obj1;}
if (p._keyId2 === keyId) {if (isBlank(this._obj2)){this._obj2 = this._new(p._binding2);} return this._obj2;}
if (p._keyId3 === keyId) {if (isBlank(this._obj3)){this._obj3 = this._new(p._binding3);} return this._obj3;}
if (p._keyId4 === keyId) {if (isBlank(this._obj4)){this._obj4 = this._new(p._binding4);} return this._obj4;}
if (p._keyId5 === keyId) {if (isBlank(this._obj5)){this._obj5 = this._new(p._binding5);} return this._obj5;}
if (p._keyId6 === keyId) {if (isBlank(this._obj6)){this._obj6 = this._new(p._binding6);} return this._obj6;}
if (p._keyId7 === keyId) {if (isBlank(this._obj7)){this._obj7 = this._new(p._binding7);} return this._obj7;}
if (p._keyId8 === keyId) {if (isBlank(this._obj8)){this._obj8 = this._new(p._binding8);} return this._obj8;}
if (p._keyId9 === keyId) {if (isBlank(this._obj9)){this._obj9 = this._new(p._binding9);} return this._obj9;}
return _undefined;
}
getDirectiveAtIndex(index:int) {
if (index == 0) return this._obj0;
if (index == 1) return this._obj1;
if (index == 2) return this._obj2;
if (index == 3) return this._obj3;
if (index == 4) return this._obj4;
if (index == 5) return this._obj5;
if (index == 6) return this._obj6;
if (index == 7) return this._obj7;
if (index == 8) return this._obj8;
if (index == 9) return this._obj9;
throw new OutOfBoundsAccess(index);
}
hasInstances() {
return this._constructionCounter > 0;
}
/** Gets whether this element is exporting a component instance as $implicit. */
isExportingComponent() {
return this._proto.exportComponent;
}
/** Gets whether this element is exporting its element as $implicit. */
isExportingElement() {
return this._proto.exportElement;
}
/** Get the name to which this element's $implicit is to be assigned. */
getExportImplicitName() {
return this._proto.exportImplicitName;
}
getLightDomAppInjector() {
return this._lightDomAppInjector;
}
getShadowDomAppInjector() {
return this._shadowDomAppInjector;
}
getHost() {
return this._host;
}
getBoundElementIndex() {
return this._proto.index;
}
}
class OutOfBoundsAccess extends BaseException {
message:string;
constructor(index) {
super();
this.message = `Index ${index} is out-of-bounds.`;
}
toString() {
return this.message;
}
}
class QueryError extends BaseException {
message:string;
// TODO(rado): pass the names of the active directives.
constructor() {
super();
this.message = 'Only 3 queries can be concurrently active in a template.';
}
toString() {
return this.message;
}
}
class QueryRef {
directive;
list: QueryList;
originator: ElementInjector;
constructor(directive, list: QueryList, originator: ElementInjector) {
this.directive = directive;
this.list = list;
this.originator = originator;
}
update() {
var aggregator = [];
this.visit(this.originator, aggregator);
this.list.reset(aggregator);
}
visit(inj: ElementInjector, aggregator) {
if (isBlank(inj)) return;
if (inj.hasDirective(this.directive)) {
ListWrapper.push(aggregator, inj.get(this.directive));
}
var child = inj._head;
while (isPresent(child)) {
this.visit(child, aggregator);
child = child._next;
}
}
}
|
ajax/libs/gumby/2.6.0/js/libs/jquery-1.10.1.min.js | gabel/cdnjs | /*! jQuery v1.10.1 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery-1.10.1.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.1",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=lt(),k=lt(),E=lt(),S=!1,A=function(){return 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=bt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+xt(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 At(e.replace(z,"$1"),t,n,i)}function st(e){return K.test(e+"")}function lt(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function ut(e){return e[b]=!0,e}function ct(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function pt(e,t,n){e=e.split("|");var r,i=e.length,a=n?null:t;while(i--)(r=o.attrHandle[e[i]])&&r!==t||(o.attrHandle[e[i]]=a)}function ft(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:e[t]===!0?t.toLowerCase():null}function dt(e,t){return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}function ht(e){return"input"===e.nodeName.toLowerCase()?e.defaultValue:t}function gt(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 mt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function yt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function vt(e){return ut(function(t){return t=+t,ut(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.parentWindow;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.frameElement&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ct(function(e){return e.innerHTML="<a href='#'></a>",pt("type|href|height|width",dt,"#"===e.firstChild.getAttribute("href")),pt(B,ft,null==e.getAttribute("disabled")),e.className="i",!e.getAttribute("className")}),r.input=ct(function(e){return e.innerHTML="<input>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")}),pt("value",ht,r.attributes&&r.input),r.getElementsByTagName=ct(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ct(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=ct(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=st(n.querySelectorAll))&&(ct(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")}),ct(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=st(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ct(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=st(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},r.sortDetached=ct(function(e){return 1&e.compareDocumentPosition(n.createElement("div"))}),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 gt(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?gt(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:ut,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=bt(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())?ut(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:ut(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?ut(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:ut(function(e){return function(t){return at(e,t).length>0}}),contains:ut(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:ut(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:vt(function(){return[0]}),last:vt(function(e,t){return[t-1]}),eq:vt(function(e,t,n){return[0>n?n+t:n]}),even:vt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:vt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:vt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:vt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=mt(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=yt(n);function bt(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 xt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function wt(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 Tt(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 Ct(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 Nt(e,t,n,r,i,o){return r&&!r[b]&&(r=Nt(r)),i&&!i[b]&&(i=Nt(i,o)),ut(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||St(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:Ct(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=Ct(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=Ct(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function kt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=wt(function(e){return e===t},s,!0),p=wt(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=[wt(Tt(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 Nt(l>1&&Tt(f),l>1&&xt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&kt(e.slice(l,r)),i>r&&kt(e=e.slice(r)),i>r&&xt(e))}f.push(n)}return Tt(f)}function Et(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=Ct(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?ut(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=bt(e)),n=t.length;while(n--)o=kt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Et(i,r))}return o};function St(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function At(e,t,n,i){var a,s,u,c,p,f=bt(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&&xt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}o.pseudos.nth=o.pseudos.eq;function jt(){}jt.prototype=o.filters=o.pseudos,o.setFilters=new jt,r.sortStable=b.split("").sort(A).join("")===b,p(),[0,0].sort(A),r.detectDuplicates=S,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 t=t||[],t=[e,t.slice?t.slice():t],!l||i&&!u||(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,r="boolean"==typeof t;return 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 o,a=0,s=x(this),l=t,u=e.match(T)||[];while(o=u[a++])l=r?l:!s.hasClass(o),s[l?"addClass":"removeClass"](o)}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){var t="boolean"==typeof e;return this.each(function(){(t?e: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,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);
|
src/svg-icons/av/music-video.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvMusicVideo = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zM8 15c0-1.66 1.34-3 3-3 .35 0 .69.07 1 .18V6h5v2h-3v7.03c-.02 1.64-1.35 2.97-3 2.97-1.66 0-3-1.34-3-3z"/>
</SvgIcon>
);
AvMusicVideo = pure(AvMusicVideo);
AvMusicVideo.displayName = 'AvMusicVideo';
AvMusicVideo.muiName = 'SvgIcon';
export default AvMusicVideo;
|
docs/src/pages/components/skeleton/SkeletonChildren.js | lgollut/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Avatar from '@material-ui/core/Avatar';
import Grid from '@material-ui/core/Grid';
import { makeStyles } from '@material-ui/core/styles';
import Skeleton from '@material-ui/lab/Skeleton';
const useStyles = makeStyles(() => ({
image: {
width: '100%',
},
}));
function SkeletonChildrenDemo(props) {
const { loading = false } = props;
const classes = useStyles();
return (
<div>
<Box display="flex" alignItems="center">
<Box margin={1}>
{loading ? (
<Skeleton variant="circle">
<Avatar />
</Skeleton>
) : (
<Avatar src="https://pbs.twimg.com/profile_images/877631054525472768/Xp5FAPD5_reasonably_small.jpg" />
)}
</Box>
<Box width="100%">
{loading ? (
<Skeleton width="100%">
<Typography>.</Typography>
</Skeleton>
) : (
<Typography>Ted</Typography>
)}
</Box>
</Box>
{loading ? (
<Skeleton variant="rect" width="100%">
<div style={{ paddingTop: '57%' }} />
</Skeleton>
) : (
<img
className={classes.image}
src="https://pi.tedcdn.com/r/talkstar-photos.s3.amazonaws.com/uploads/72bda89f-9bbf-4685-910a-2f151c4f3a8a/NicolaSturgeon_2019T-embed.jpg?w=512"
alt=""
/>
)}
</div>
);
}
SkeletonChildrenDemo.propTypes = {
loading: PropTypes.bool,
};
export default function SkeletonChildren() {
return (
<Grid container spacing={8}>
<Grid item xs>
<SkeletonChildrenDemo loading />
</Grid>
<Grid item xs>
<SkeletonChildrenDemo />
</Grid>
</Grid>
);
}
|
src/components/RegistrationForm/RegistrationForm.js | ThomasBem/ps-react-thomasbem | import React from 'react';
import PropTypes from 'prop-types';
import TextInput from '../TextInput';
import PasswordInput from '../PasswordInput';
/** Registration form with built-in validation. */
class RegistrationForm extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {
email: '',
password: ''
},
errors: {},
submitted: false,
};
}
onChange = (event) => {
const user = this.state.user;
user[event.target.name] = event.target.value;
this.setState({user});
}
// Returns a number from 0 to 100 that represents password quality.
// For simplicity, just returning % of min length entered.
// Could enhance with checks for number, special char, unique characters, etc.
passwordQuality(password) {
if (!password) return null;
if (password.length >= this.props.minPasswordLength) return 100;
const percentOfMinLength = parseInt(password.length/this.props.minPasswordLength * 100, 10);
return percentOfMinLength;
}
validate({email, password}) {
const errors = {};
const {minPasswordLength} = this.props;
if (!email) errors.email = 'Email required.';
if (password.length < minPasswordLength) errors.password = `Password must be at least ${minPasswordLength} characters.`;
this.setState({errors});
const formIsValid = Object.getOwnPropertyNames(errors).length === 0;
return formIsValid;
}
onSubmit = () => {
const {user} = this.state;
const formIsValid = this.validate(user);
if (formIsValid) {
this.props.onSubmit(user);
this.setState({submitted: true});
}
}
render() {
const {errors, submitted} = this.state;
const {email, password} = this.state.user;
return (
submitted ?
<h2>{this.props.confirmationMessage}</h2> :
<div>
<TextInput
htmlId="registration-form-email"
name="email"
onChange={this.onChange}
label="Email"
value={email}
error={errors.email}
required />
<PasswordInput
htmlId="registration-form-password"
name="password"
value={password}
onChange={this.onChange}
quality={this.passwordQuality(password)}
showVisibilityToggle
maxLength={50}
error={errors.password} />
<input type="submit" value="Register" onClick={this.onSubmit} />
</div>
)
}
}
RegistrationForm.propTypes = {
/** Message displayed upon successful submission */
confirmationMessage: PropTypes.string,
/** Called when form is submitted */
onSubmit: PropTypes.func.isRequired,
/** Minimum password length */
minPasswordLength: PropTypes.number
}
RegistrationForm.defaultProps = {
confirmationMessage: "Thanks for registering!",
minPasswordLength: 8
};
export default RegistrationForm; |
ajax/libs/jointjs/0.8.0/joint.nobackbone.js | blairvanderhoof/cdnjs | /*! JointJS v0.8.0 - JavaScript diagramming library 2014-01-22
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*!
* jQuery JavaScript Library v1.9.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-2-4
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<9
// For `typeof node.method` instead of `node.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.9.1",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support, all, a,
input, select, fragment,
opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType === 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
checkOn: !!input.value,
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: document.compatMode === "CSS1Compat",
// Will be defined later
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var i, l, thisCache,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
// Try to fetch any internally stored data first
return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
}
this.each(function() {
jQuery.data( this, key, value );
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
hooks.cur = fn;
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, notxml, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
// In IE9+, Flash objects don't have .getAttribute (#12945)
// Support: IE9+
if ( typeof elem.getAttribute !== core_strundefined ) {
ret = elem.getAttribute( name );
}
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( rboolean.test( name ) ) {
// Set corresponding property to false for boolean attributes
// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8
if ( !getSetAttribute && ruseDefault.test( name ) ) {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
} else {
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
var
// Use .prop to determine if this attribute is understood as boolean
prop = jQuery.prop( elem, name ),
// Fetch it accordingly
attr = typeof prop === "boolean" && elem.getAttribute( name ),
detail = typeof prop === "boolean" ?
getSetInput && getSetAttribute ?
attr != null :
// oldIE fabricates an empty string for missing boolean attributes
// and conflates checked/selected into attroperties
ruseDefault.test( name ) ?
elem[ jQuery.camelCase( "default-" + name ) ] :
!!attr :
// fetch an attribute node for properties not recognized as boolean
elem.getAttributeNode( name );
return detail && detail.value !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// fix oldIE value attroperty
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return jQuery.nodeName( elem, "input" ) ?
// Ignore the value *property* by using defaultValue
elem.defaultValue :
ret && ret.specified ? ret.value : undefined;
},
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret == null ? undefined : ret;
}
});
});
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
event.isTrigger = true;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur != this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
}
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== document.activeElement && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === document.activeElement && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
hasDuplicate,
outermostContext,
// Local document vars
setDocument,
document,
docElem,
documentIsXML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
sortOrder,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /^[^{]+\{\s*\[native code/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function( _, escaped ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Use a stripped-down slice if we can't use a native one
try {
slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
while ( (elem = this[i++]) ) {
results.push( elem );
}
return results;
};
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( !documentIsXML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
// QSA path
if ( support.qsa && !rbuggyQSA.test(selector) ) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsXML = isXML( doc );
// Check if getElementsByTagName("*") returns only elements
support.tagNameNoComments = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getByClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
support.getByName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName( expando + 0 ).length;
support.getIdNotName = !doc.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
// ID find and filter
if ( support.getIdNotName ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.tagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
// Class
Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
return context.getElementsByClassName( className );
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if ( div.querySelectorAll("[i^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
var compare;
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
if ( a === doc || contains( preferredDoc, a ) ) {
return -1;
}
if ( b === doc || contains( preferredDoc, b ) ) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
hasDuplicate = false;
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyQSA always contains :focus, so no need for an existence check
if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
var val;
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
if ( !documentIsXML ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( documentIsXML || support.attributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifider
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsXML ?
elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
elem.lang) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !documentIsXML &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
documentIsXML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Initialize with the default document
setDocument();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, ret, self,
len = this.length;
if ( typeof selector !== "string" ) {
self = this;
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
ret = [];
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, this[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = ( this.selector ? this.selector + " " : "" ) + selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true) );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
var isFunc = jQuery.isFunction( value );
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( !isFunc && typeof value !== "string" ) {
value = jQuery( value ).not( this ).detach();
}
return this.domManip( [ value ], true, function( elem ) {
var next = this.nextSibling,
parent = this.parentNode;
if ( parent ) {
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
});
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, table ? self.html() : undefined );
}
self.domManip( args, table, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
node,
i
);
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery.ajax({
url: node.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
var attr = elem.getAttributeNode("type");
elem.type = ( attr && attr.specified ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.hover = function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
};
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 ) {
isSuccess = true;
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
isSuccess = true;
statusText = "notmodified";
// If we have data, let's convert it
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv2, current, conv, tmp,
converters = {},
i = 0,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ];
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( err ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var value, name, index, easing, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
/*jshint validthis:true */
var prop, index, length,
value, dataShow, toggle,
tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
doAnimation.finish = function() {
anim.stop( true );
};
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.cur && hooks.cur.finish ) {
hooks.cur.finish.call( this );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.documentElement;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// })();
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
/**
* jQuery.fn.sortElements
* --------------
* @author James Padolsey (http://james.padolsey.com)
* @version 0.11
* @updated 18-MAR-2010
* --------------
* @param Function comparator:
* Exactly the same behaviour as [1,2,3].sort(comparator)
*
* @param Function getSortable
* A function that should return the element that is
* to be sorted. The comparator will run on the
* current collection, but you may want the actual
* resulting sort to occur on a parent or another
* associated element.
*
* E.g. $('td').sortElements(comparator, function(){
* return this.parentNode;
* })
*
* The <td>'s parent (<tr>) will be sorted instead
* of the <td> itself.
*/
jQuery.fn.sortElements = (function(){
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function(){return this;};
var placements = this.map(function(){
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
// Since the element itself will change position, we have
// to have some way of storing it's original position in
// the DOM. The easiest way is to have a 'flag' node:
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i){
placements[i].call(getSortable.call(this));
});
};
})();
// JointJS library.
// (c) 2011-2013 client IO
if (typeof exports === 'object') {
var _ = require('lodash');
}
// Global namespace.
var joint = {
// `joint.dia` namespace.
dia: {},
// `joint.ui` namespace.
ui: {},
// `joint.layout` namespace.
layout: {},
// `joint.shapes` namespace.
shapes: {},
// `joint.format` namespace.
format: {},
util: {
// Return a simple hash code from a string. See http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/.
hashCode: function(str) {
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
hash = ((hash << 5) - hash) + c;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
},
getByPath: function(obj, path, delim) {
delim = delim || '.';
var keys = path.split(delim);
var key;
while (keys.length) {
key = keys.shift();
if (key in obj) {
obj = obj[key];
} else {
return undefined;
}
}
return obj;
},
setByPath: function(obj, path, value, delim) {
delim = delim || '.';
var keys = path.split(delim);
var diver = obj;
var i = 0;
if (path.indexOf(delim) > -1) {
for (var len = keys.length; i < len - 1; i++) {
// diver creates an empty object if there is no nested object under such a key.
// This means that one can populate an empty nested object with setByPath().
diver = diver[keys[i]] || (diver[keys[i]] = {});
}
diver[keys[len - 1]] = value;
} else {
obj[path] = value;
}
return obj;
},
flattenObject: function(obj, delim, stop) {
delim = delim || '.';
var ret = {};
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
var shouldGoDeeper = typeof obj[key] === 'object';
if (shouldGoDeeper && stop && stop(obj[key])) {
shouldGoDeeper = false;
}
if (shouldGoDeeper) {
var flatObject = this.flattenObject(obj[key], delim, stop);
for (var flatKey in flatObject) {
if (!flatObject.hasOwnProperty(flatKey)) continue;
ret[key + delim + flatKey] = flatObject[flatKey];
}
} else {
ret[key] = obj[key];
}
}
return ret;
},
uuid: function() {
// credit: http://stackoverflow.com/posts/2117523/revisions
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
},
// Generate global unique id for obj and store it as a property of the object.
guid: function(obj) {
this.guid.id = this.guid.id || 1;
obj.id = (obj.id === undefined ? 'j_' + this.guid.id++ : obj.id);
return obj.id;
},
// Copy all the properties to the first argument from the following arguments.
// All the properties will be overwritten by the properties from the following
// arguments. Inherited properties are ignored.
mixin: function() {
var target = arguments[0];
for (var i = 1, l = arguments.length; i < l; i++) {
var extension = arguments[i];
// Only functions and objects can be mixined.
if ((Object(extension) !== extension) &&
!_.isFunction(extension) &&
(extension === null || extension === undefined)) {
continue;
}
_.each(extension, function(copy, key) {
if (this.mixin.deep && (Object(copy) === copy)) {
if (!target[key]) {
target[key] = _.isArray(copy) ? [] : {};
}
this.mixin(target[key], copy);
return;
}
if (target[key] !== copy) {
if (!this.mixin.supplement || !target.hasOwnProperty(key)) {
target[key] = copy;
}
}
}, this);
}
return target;
},
// Copy all properties to the first argument from the following
// arguments only in case if they don't exists in the first argument.
// All the function propererties in the first argument will get
// additional property base pointing to the extenders same named
// property function's call method.
supplement: function() {
this.mixin.supplement = true;
var ret = this.mixin.apply(this, arguments);
this.mixin.supplement = false;
return ret;
},
// Same as `mixin()` but deep version.
deepMixin: function() {
this.mixin.deep = true;
var ret = this.mixin.apply(this, arguments);
this.mixin.deep = false;
return ret;
},
// Same as `supplement()` but deep version.
deepSupplement: function() {
this.mixin.deep = this.mixin.supplement = true;
var ret = this.mixin.apply(this, arguments);
this.mixin.deep = this.mixin.supplement = false;
return ret;
},
normalizeEvent: function(evt) {
return (evt.originalEvent && evt.originalEvent.changedTouches && evt.originalEvent.changedTouches.length) ? evt.originalEvent.changedTouches[0] : evt;
},
nextFrame:(function() {
var raf;
var client = typeof window != 'undefined';
if (client) {
raf = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
}
if (!raf) {
var lastTime = 0;
raf = function(callback) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
return client ? _.bind(raf, window) : raf;
})(),
cancelFrame: (function() {
var caf;
var client = typeof window != 'undefined';
if (client) {
caf = window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.msCancelAnimationFrame ||
window.msCancelRequestAnimationFrame ||
window.oCancelAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.mozCancelAnimationFrame ||
window.mozCancelRequestAnimationFrame;
}
caf = caf || clearTimeout;
return client ? _.bind(caf, window) : caf;
})(),
timing: {
linear: function(t) {
return t;
},
quad: function(t) {
return t * t;
},
cubic: function(t) {
return t * t * t;
},
inout: function(t) {
if (t <= 0) return 0;
if (t >= 1) return 1;
var t2 = t * t, t3 = t2 * t;
return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
},
exponential: function(t) {
return Math.pow(2, 10 * (t - 1));
},
bounce: function(t) {
for(var a = 0, b = 1; 1; a += b, b /= 2) {
if (t >= (7 - 4 * a) / 11) {
var q = (11 - 6 * a - 11 * t) / 4;
return -q * q + b * b;
}
}
},
reverse: function(f) {
return function(t) {
return 1 - f(1 - t)
}
},
reflect: function(f) {
return function(t) {
return .5 * (t < .5 ? f(2 * t) : (2 - f(2 - 2 * t)));
};
},
clamp: function(f,n,x) {
n = n || 0;
x = x || 1;
return function(t) {
var r = f(t);
return r < n ? n : r > x ? x : r;
}
},
back: function(s) {
if (!s) s = 1.70158;
return function(t) {
return t * t * ((s + 1) * t - s);
};
},
elastic: function(x) {
if (!x) x = 1.5;
return function(t) {
return Math.pow(2, 10 * (t - 1)) * Math.cos(20*Math.PI*x/3*t);
}
}
},
interpolate: {
number: function(a, b) {
var d = b - a;
return function(t) { return a + d * t; };
},
object: function(a, b) {
var s = _.keys(a);
return function(t) {
var i, p, r = {};
for (i = s.length - 1; i != -1; i--) {
p = s[i];
r[p] = a[p] + (b[p] - a[p]) * t;
}
return r;
}
},
hexColor: function(a, b) {
var ca = parseInt(a.slice(1), 16), cb = parseInt(b.slice(1), 16);
var ra = ca & 0x0000ff, rd = (cb & 0x0000ff) - ra;
var ga = ca & 0x00ff00, gd = (cb & 0x00ff00) - ga;
var ba = ca & 0xff0000, bd = (cb & 0xff0000) - ba;
return function(t) {
return '#' + (1 << 24 |(ra + rd * t)|(ga + gd * t)|(ba + bd * t)).toString(16).slice(1);
};
},
unit: function(a, b) {
var r = /(-?[0-9]*.[0-9]*)(px|em|cm|mm|in|pt|pc|%)/;
var ma = r.exec(a), mb = r.exec(b);
var p = mb[1].indexOf('.'), f = p > 0 ? mb[1].length - p - 1 : 0;
var a = +ma[1], d = +mb[1] - a, u = ma[2];
return function(t) {
return (a + d * t).toFixed(f) + u;
}
}
},
// SVG filters.
filter: {
// `x` ... horizontal blur
// `y` ... vertical blur (optional)
blur: function(args) {
var x = _.isFinite(args.x) ? args.x : 2;
return _.template('<filter><feGaussianBlur stdDeviation="${stdDeviation}"/></filter>', {
stdDeviation: _.isFinite(args.y) ? [x, args.y] : x
});
},
// `dx` ... horizontal shift
// `dy` ... vertical shift
// `blur` ... blur
// `color` ... color
dropShadow: function(args) {
return _.template('<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>', {
dx: args.dx || 0,
dy: args.dy || 0,
color: args.color || 'black',
blur: _.isFinite(args.blur) ? args.blur : 4
});
},
// `amount` ... the proportion of the conversion. A value of 1 is completely grayscale. A value of 0 leaves the input unchanged.
grayscale: function(args) {
var amount = _.isFinite(args.amount) ? args.amount : 1;
return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/></filter>', {
a: 0.2126 + 0.7874 * (1 - amount),
b: 0.7152 - 0.7152 * (1 - amount),
c: 0.0722 - 0.0722 * (1 - amount),
d: 0.2126 - 0.2126 * (1 - amount),
e: 0.7152 + 0.2848 * (1 - amount),
f: 0.0722 - 0.0722 * (1 - amount),
g: 0.2126 - 0.2126 * (1 - amount),
h: 0.0722 + 0.9278 * (1 - amount)
});
},
// `amount` ... the proportion of the conversion. A value of 1 is completely sepia. A value of 0 leaves the input unchanged.
sepia: function(args) {
var amount = _.isFinite(args.amount) ? args.amount : 1;
return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${h} ${i} 0 0 0 0 0 1 0"/></filter>', {
a: 0.393 + 0.607 * (1 - amount),
b: 0.769 - 0.769 * (1 - amount),
c: 0.189 - 0.189 * (1 - amount),
d: 0.349 - 0.349 * (1 - amount),
e: 0.686 + 0.314 * (1 - amount),
f: 0.168 - 0.168 * (1 - amount),
g: 0.272 - 0.272 * (1 - amount),
h: 0.534 - 0.534 * (1 - amount),
i: 0.131 + 0.869 * (1 - amount)
});
},
// `amount` ... the proportion of the conversion. A value of 0 is completely un-saturated. A value of 1 leaves the input unchanged.
saturate: function(args) {
var amount = _.isFinite(args.amount) ? args.amount : 1;
return _.template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>', {
amount: 1 - amount
});
},
// `angle` ... the number of degrees around the color circle the input samples will be adjusted.
hueRotate: function(args) {
return _.template('<filter><feColorMatrix type="hueRotate" values="${angle}"/></filter>', {
angle: args.angle || 0
});
},
// `amount` ... the proportion of the conversion. A value of 1 is completely inverted. A value of 0 leaves the input unchanged.
invert: function(args) {
var amount = _.isFinite(args.amount) ? args.amount : 1;
return _.template('<filter><feComponentTransfer><feFuncR type="table" tableValues="${amount} ${amount2}"/><feFuncG type="table" tableValues="${amount} ${amount2}"/><feFuncB type="table" tableValues="${amount} ${amount2}"/></feComponentTransfer></filter>', {
amount: amount,
amount2: 1 - amount
});
},
// `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged.
brightness: function(args) {
return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}"/><feFuncG type="linear" slope="${amount}"/><feFuncB type="linear" slope="${amount}"/></feComponentTransfer></filter>', {
amount: _.isFinite(args.amount) ? args.amount : 1
});
},
// `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged.
contrast: function(args) {
var amount = _.isFinite(args.amount) ? args.amount : 1;
return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}" intercept="${amount2}"/><feFuncG type="linear" slope="${amount}" intercept="${amount2}"/><feFuncB type="linear" slope="${amount}" intercept="${amount2}"/></feComponentTransfer></filter>', {
amount: amount,
amount2: .5 - amount / 2
});
}
}
}
};
if (typeof exports === 'object') {
module.exports = joint;
}
// Vectorizer.
// -----------
// A tiny library for making your live easier when dealing with SVG.
// Copyright © 2012 - 2013 client IO
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['lodash'], factory);
} else {
// Browser globals.
root.Vectorizer = root.V = factory(root._);
}
}(this, function(_) {
// Well, if SVG is not supported, this library is useless.
var SVGsupported = !!(window.SVGAngle || document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1'));
// XML namespaces.
var ns = {
xmlns: 'http://www.w3.org/2000/svg',
xlink: 'http://www.w3.org/1999/xlink'
};
// SVG version.
var SVGversion = '1.1';
// Create SVG element.
// -------------------
function createElement(el, attrs, children) {
if (!el) return undefined;
// If `el` is an object, it is probably a native SVG element. Wrap it to VElement.
if (typeof el === 'object') {
return new VElement(el);
}
attrs = attrs || {};
// If `el` is a `'svg'` or `'SVG'` string, create a new SVG canvas.
if (el.toLowerCase() === 'svg') {
attrs.xmlns = ns.xmlns;
attrs['xmlns:xlink'] = ns.xlink;
attrs.version = SVGversion;
} else if (el[0] === '<') {
// Create element from an SVG string.
// Allows constructs of type: `document.appendChild(Vectorizer('<rect></rect>').node)`.
var svg = '<svg xmlns="' + ns.xmlns + '" xmlns:xlink="' + ns.xlink + '" version="' + SVGversion + '">' + el + '</svg>';
var parser = new DOMParser();
parser.async = false;
var svgDoc = parser.parseFromString(svg, 'text/xml').documentElement;
// Note that `createElement()` might also return an array should the SVG string passed as
// the first argument contain more then one root element.
if (svgDoc.childNodes.length > 1) {
return _.map(svgDoc.childNodes, function(childNode) {
return new VElement(document.importNode(childNode, true));
});
}
return new VElement(document.importNode(svgDoc.firstChild, true));
}
el = document.createElementNS(ns.xmlns, el);
// Set attributes.
for (var key in attrs) {
setAttribute(el, key, attrs[key]);
}
// Normalize `children` array.
if (Object.prototype.toString.call(children) != '[object Array]') children = [children];
// Append children if they are specified.
var i = 0, len = (children[0] && children.length) || 0, child;
for (; i < len; i++) {
child = children[i];
el.appendChild(child instanceof VElement ? child.node : child);
}
return new VElement(el);
}
function setAttribute(el, name, value) {
if (name.indexOf(':') > -1) {
// Attribute names can be namespaced. E.g. `image` elements
// have a `xlink:href` attribute to set the source of the image.
var combinedKey = name.split(':');
el.setAttributeNS(ns[combinedKey[0]], combinedKey[1], value);
} else if (name === 'id') {
el.id = value;
} else {
el.setAttribute(name, value);
}
}
function parseTransformString(transform) {
var translate,
rotate,
scale;
if (transform) {
var translateMatch = transform.match(/translate\((.*)\)/);
if (translateMatch) {
translate = translateMatch[1].split(',');
}
var rotateMatch = transform.match(/rotate\((.*)\)/);
if (rotateMatch) {
rotate = rotateMatch[1].split(',');
}
var scaleMatch = transform.match(/scale\((.*)\)/);
if (scaleMatch) {
scale = scaleMatch[1].split(',');
}
}
var sx = (scale && scale[0]) ? parseFloat(scale[0]) : 1;
return {
translate: {
tx: (translate && translate[0]) ? parseInt(translate[0], 10) : 0,
ty: (translate && translate[1]) ? parseInt(translate[1], 10) : 0
},
rotate: {
angle: (rotate && rotate[0]) ? parseInt(rotate[0], 10) : 0,
cx: (rotate && rotate[1]) ? parseInt(rotate[1], 10) : undefined,
cy: (rotate && rotate[2]) ? parseInt(rotate[2], 10) : undefined
},
scale: {
sx: sx,
sy: (scale && scale[1]) ? parseFloat(scale[1]) : sx
}
};
}
// Matrix decomposition.
// ---------------------
function deltaTransformPoint(matrix, point) {
var dx = point.x * matrix.a + point.y * matrix.c + 0;
var dy = point.x * matrix.b + point.y * matrix.d + 0;
return { x: dx, y: dy };
}
function decomposeMatrix(matrix) {
// @see https://gist.github.com/2052247
// calculate delta transform point
var px = deltaTransformPoint(matrix, { x: 0, y: 1 });
var py = deltaTransformPoint(matrix, { x: 1, y: 0 });
// calculate skew
var skewX = ((180 / Math.PI) * Math.atan2(px.y, px.x) - 90);
var skewY = ((180 / Math.PI) * Math.atan2(py.y, py.x));
return {
translateX: matrix.e,
translateY: matrix.f,
scaleX: Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b),
scaleY: Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d),
skewX: skewX,
skewY: skewY,
rotation: skewX // rotation is the same as skew x
};
}
// VElement.
// ---------
function VElement(el) {
this.node = el;
if (!this.node.id) {
this.node.id = _.uniqueId('v_');
}
}
// VElement public API.
// --------------------
VElement.prototype = {
translate: function(tx, ty) {
ty = ty || 0;
var transformAttr = this.attr('transform') || '',
transform = parseTransformString(transformAttr);
// Is it a getter?
if (typeof tx === 'undefined') {
return transform.translate;
}
transformAttr = transformAttr.replace(/translate\([^\)]*\)/g, '').trim();
var newTx = transform.translate.tx + tx,
newTy = transform.translate.ty + ty;
// Note that `translate()` is always the first transformation. This is
// usually the desired case.
this.attr('transform', 'translate(' + newTx + ',' + newTy + ') ' + transformAttr);
return this;
},
rotate: function(angle, cx, cy) {
var transformAttr = this.attr('transform') || '',
transform = parseTransformString(transformAttr);
// Is it a getter?
if (typeof angle === 'undefined') {
return transform.rotate;
}
transformAttr = transformAttr.replace(/rotate\([^\)]*\)/g, '').trim();
var newAngle = transform.rotate.angle + angle % 360,
newOrigin = (cx !== undefined && cy !== undefined) ? ',' + cx + ',' + cy : '';
this.attr('transform', transformAttr + ' rotate(' + newAngle + newOrigin + ')');
return this;
},
// Note that `scale` as the only transformation does not combine with previous values.
scale: function(sx, sy) {
sy = (typeof sy === 'undefined') ? sx : sy;
var transformAttr = this.attr('transform') || '',
transform = parseTransformString(transformAttr);
// Is it a getter?
if (typeof sx === 'undefined') {
return transform.scale;
}
transformAttr = transformAttr.replace(/scale\([^\)]*\)/g, '').trim();
this.attr('transform', transformAttr + ' scale(' + sx + ',' + sy + ')');
return this;
},
// Get SVGRect that contains coordinates and dimension of the real bounding box,
// i.e. after transformations are applied.
// If `target` is specified, bounding box will be computed relatively to `target` element.
bbox: function(withoutTransformations, target) {
// If the element is not in the live DOM, it does not have a bounding box defined and
// so fall back to 'zero' dimension element.
if (!this.node.ownerSVGElement) return { x: 0, y: 0, width: 0, height: 0 };
var box;
try {
box = this.node.getBBox();
// Opera returns infinite values in some cases.
// Note that Infinity | 0 produces 0 as opposed to Infinity || 0.
// We also have to create new object as the standard says that you can't
// modify the attributes of a bbox.
box = { x: box.x | 0, y: box.y | 0, width: box.width | 0, height: box.height | 0};
} catch (e) {
// Fallback for IE.
box = {
x: this.node.clientLeft,
y: this.node.clientTop,
width: this.node.clientWidth,
height: this.node.clientHeight
};
}
if (withoutTransformations) {
return box;
}
var matrix = this.node.getTransformToElement(target || this.node.ownerSVGElement);
var corners = [];
var point = this.node.ownerSVGElement.createSVGPoint();
point.x = box.x;
point.y = box.y;
corners.push(point.matrixTransform(matrix));
point.x = box.x + box.width;
point.y = box.y;
corners.push(point.matrixTransform(matrix));
point.x = box.x + box.width;
point.y = box.y + box.height;
corners.push(point.matrixTransform(matrix));
point.x = box.x;
point.y = box.y + box.height;
corners.push(point.matrixTransform(matrix));
var minX = corners[0].x;
var maxX = minX;
var minY = corners[0].y;
var maxY = minY;
for (var i = 1, len = corners.length; i < len; i++) {
var x = corners[i].x;
var y = corners[i].y;
if (x < minX) {
minX = x;
} else if (x > maxX) {
maxX = x;
}
if (y < minY) {
minY = y;
} else if (y > maxY) {
maxY = y;
}
}
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY
};
},
text: function(content) {
var lines = content.split('\n'), i = 0,
tspan;
// `alignment-baseline` does not work in Firefox.
// Setting `dominant-baseline` on the `<text>` element doesn't work in IE9.
// In order to have the 0,0 coordinate of the `<text>` element (or the first `<tspan>`)
// in the top left corner we translate the `<text>` element by `0.8em`.
// See `http://www.w3.org/Graphics/SVG/WG/wiki/How_to_determine_dominant_baseline`.
// See also `http://apike.ca/prog_svg_text_style.html`.
this.attr('y', '0.8em');
if (lines.length === 1) {
this.node.textContent = content;
return this;
}
// Easy way to erase all `<tspan>` children;
this.node.textContent = '';
for (; i < lines.length; i++) {
// Shift all the <tspan> but first by one line (`1em`)
tspan = V('tspan', { dy: (i == 0 ? '0em' : '1em'), x: this.attr('x') || 0});
tspan.node.textContent = lines[i];
this.append(tspan);
}
return this;
},
attr: function(name, value) {
if (typeof name === 'string' && typeof value === 'undefined') {
return this.node.getAttribute(name);
}
if (typeof name === 'object') {
_.each(name, function(value, name) {
setAttribute(this.node, name, value);
}, this);
} else {
setAttribute(this.node, name, value);
}
return this;
},
remove: function() {
if (this.node.parentNode) {
this.node.parentNode.removeChild(this.node);
}
},
append: function(el) {
var els = el;
if (!_.isArray(el)) {
els = [el];
}
_.each(els, function(el) {
this.node.appendChild(el instanceof VElement ? el.node : el);
}, this);
return this;
},
prepend: function(el) {
this.node.insertBefore(el instanceof VElement ? el.node : el, this.node.firstChild);
},
svg: function() {
return this.node instanceof window.SVGSVGElement ? this : V(this.node.ownerSVGElement);
},
defs: function() {
var defs = this.svg().node.getElementsByTagName('defs');
return (defs && defs.length) ? V(defs[0]) : undefined;
},
clone: function() {
var clone = V(this.node.cloneNode(true));
// Note that clone inherits also ID. Therefore, we need to change it here.
clone.node.id = _.uniqueId('v-');
return clone;
},
// Convert global point into the coordinate space of this element.
toLocalPoint: function(x, y) {
var svg = this.svg().node;
var p = svg.createSVGPoint();
p.x = x;
p.y = y;
try {
var globalPoint = p.matrixTransform(svg.getScreenCTM().inverse());
var globalToLocalMatrix = this.node.getTransformToElement(svg).inverse();
} catch(e) {
// IE9 throws an exception in odd cases. (`Unexpected call to method or property access`)
// We have to make do with the original coordianates.
return p;
}
return globalPoint.matrixTransform(globalToLocalMatrix);
},
translateCenterToPoint: function(p) {
var bbox = this.bbox();
var center = g.rect(bbox).center();
this.translate(p.x - center.x, p.y - center.y);
},
// Efficiently auto-orient an element. This basically implements the orient=auto attribute
// of markers. The easiest way of understanding on what this does is to imagine the element is an
// arrowhead. Calling this method on the arrowhead makes it point to the `position` point while
// being auto-oriented (properly rotated) towards the `reference` point.
// `target` is the element relative to which the transformations are applied. Usually a viewport.
translateAndAutoOrient: function(position, reference, target) {
// Clean-up previously set transformations except the scale. If we didn't clean up the
// previous transformations then they'd add up with the old ones. Scale is an exception as
// it doesn't add up, consider: `this.scale(2).scale(2).scale(2)`. The result is that the
// element is scaled by the factor 2, not 8.
var s = this.scale();
this.attr('transform', '');
this.scale(s.sx, s.sy);
var svg = this.svg().node;
var bbox = this.bbox(false, target);
// 1. Translate to origin.
var translateToOrigin = svg.createSVGTransform();
translateToOrigin.setTranslate(-bbox.x - bbox.width/2, -bbox.y - bbox.height/2);
// 2. Rotate around origin.
var rotateAroundOrigin = svg.createSVGTransform();
var angle = g.point(position).changeInAngle(position.x - reference.x, position.y - reference.y, reference);
rotateAroundOrigin.setRotate(angle, 0, 0);
// 3. Translate to the `position` + the offset (half my width) towards the `reference` point.
var translateFinal = svg.createSVGTransform();
var finalPosition = g.point(position).move(reference, bbox.width/2);
translateFinal.setTranslate(position.x + (position.x - finalPosition.x), position.y + (position.y - finalPosition.y));
// 4. Apply transformations.
var ctm = this.node.getTransformToElement(target);
var transform = svg.createSVGTransform();
transform.setMatrix(
translateFinal.matrix.multiply(
rotateAroundOrigin.matrix.multiply(
translateToOrigin.matrix.multiply(
ctm)))
);
// Instead of directly setting the `matrix()` transform on the element, first, decompose
// the matrix into separate transforms. This allows us to use normal Vectorizer methods
// as they don't work on matrices. An example of this is to retrieve a scale of an element.
// this.node.transform.baseVal.initialize(transform);
var decomposition = decomposeMatrix(transform.matrix);
this.translate(decomposition.translateX, decomposition.translateY);
this.rotate(decomposition.rotation);
// Note that scale has been already applied, hence the following line stays commented. (it's here just for reference).
//this.scale(decomposition.scaleX, decomposition.scaleY);
return this;
},
animateAlongPath: function(attrs, path) {
var animateMotion = V('animateMotion', attrs);
var mpath = V('mpath', { 'xlink:href': '#' + V(path).node.id });
animateMotion.append(mpath);
this.append(animateMotion);
try {
animateMotion.node.beginElement();
} catch (e) {
// Fallback for IE 9.
// Run the animation programatically if FakeSmile (`http://leunen.me/fakesmile/`) present
if (document.documentElement.getAttribute('smiling') === 'fake') {
// Register the animation. (See `https://answers.launchpad.net/smil/+question/203333`)
var animation = animateMotion.node;
animation.animators = new Array();
var animationID = animation.getAttribute('id');
if (animationID) id2anim[animationID] = animation;
_.each(getTargets(animation), function(target, index) {
var animator = new Animator(animation, target, index);
animators.push(animator);
animation.animators[index] = animator;
});
_.invoke(animation.animators, 'register');
}
}
}
};
var V = createElement;
V.decomposeMatrix = decomposeMatrix;
var svgDocument = V('svg').node;
V.createSVGMatrix = function(m) {
return _.extend(svgDocument.createSVGMatrix(), m);
};
V.createSVGTransform = function() {
return svgDocument.createSVGTransform();
};
V.createSVGPoint = function(x, y) {
var p = svgDocument.createSVGPoint();
p.x = x;
p.y = y;
return p;
};
return V;
}));
// Geometry library.
// (c) 2011-2013 client IO
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else {
// Browser globals.
root.g = factory();
}
}(this, function() {
// Declare shorthands to the most used math functions.
var math = Math;
var abs = math.abs;
var cos = math.cos;
var sin = math.sin;
var sqrt = math.sqrt;
var mmin = math.min;
var mmax = math.max;
var atan = math.atan;
var atan2 = math.atan2;
var acos = math.acos;
var round = math.round;
var floor = math.floor;
var PI = math.PI;
var random = math.random;
var toDeg = function(rad) { return (180*rad / PI) % 360; };
var toRad = function(deg) { return (deg % 360) * PI / 180; };
var snapToGrid = function(val, gridSize) { return gridSize * Math.round(val/gridSize); };
var normalizeAngle = function(angle) { return (angle % 360) + (angle < 0 ? 360 : 0); };
// Point
// -----
// Point is the most basic object consisting of x/y coordinate,.
// Possible instantiations are:
// * `point(10, 20)`
// * `new point(10, 20)`
// * `point('10 20')`
// * `point(point(10, 20))`
function point(x, y) {
if (!(this instanceof point))
return new point(x, y);
var xy;
if (y === undefined && Object(x) !== x) {
xy = x.split(_.indexOf(x, "@") === -1 ? " " : "@");
this.x = parseInt(xy[0], 10);
this.y = parseInt(xy[1], 10);
} else if (Object(x) === x) {
this.x = x.x;
this.y = x.y;
} else {
this.x = x;
this.y = y;
}
}
point.prototype = {
toString: function() {
return this.x + "@" + this.y;
},
// If point lies outside rectangle `r`, return the nearest point on the boundary of rect `r`,
// otherwise return point itself.
// (see Squeak Smalltalk, Point>>adhereTo:)
adhereToRect: function(r) {
if (r.containsPoint(this)){
return this;
}
this.x = mmin(mmax(this.x, r.x), r.x + r.width);
this.y = mmin(mmax(this.y, r.y), r.y + r.height);
return this;
},
// Compute the angle between me and `p` and the x axis.
// (cartesian-to-polar coordinates conversion)
// Return theta angle in degrees.
theta: function(p) {
p = point(p);
// Invert the y-axis.
var y = -(p.y - this.y);
var x = p.x - this.x;
// Makes sure that the comparison with zero takes rounding errors into account.
var PRECISION = 10;
// Note that `atan2` is not defined for `x`, `y` both equal zero.
var rad = (y.toFixed(PRECISION) == 0 && x.toFixed(PRECISION) == 0) ? 0 : atan2(y, x);
// Correction for III. and IV. quadrant.
if (rad < 0) {
rad = 2*PI + rad;
}
return 180*rad / PI;
},
// Returns distance between me and point `p`.
distance: function(p) {
return line(this, p).length();
},
// Returns a manhattan (taxi-cab) distance between me and point `p`.
manhattanDistance: function(p) {
return abs(p.x - this.x) + abs(p.y - this.y);
},
// Offset me by the specified amount.
offset: function(dx, dy) {
this.x += dx || 0;
this.y += dy || 0;
return this;
},
magnitude: function() {
return sqrt((this.x*this.x) + (this.y*this.y)) || 0.01;
},
update: function(x, y) {
this.x = x || 0;
this.y = y || 0;
return this;
},
round: function(decimals) {
this.x = decimals ? this.x.toFixed(decimals) : round(this.x);
this.y = decimals ? this.y.toFixed(decimals) : round(this.y);
return this;
},
// Scale the line segment between (0,0) and me to have a length of len.
normalize: function(len) {
var s = (len || 1) / this.magnitude();
this.x = s * this.x;
this.y = s * this.y;
return this;
},
difference: function(p) {
return point(this.x - p.x, this.y - p.y);
},
// Converts rectangular to polar coordinates.
// An origin can be specified, otherwise it's 0@0.
toPolar: function(o) {
o = (o && point(o)) || point(0,0);
var x = this.x;
var y = this.y;
this.x = sqrt((x-o.x)*(x-o.x) + (y-o.y)*(y-o.y)); // r
this.y = toRad(o.theta(point(x,y)));
return this;
},
// Rotate point by angle around origin o.
rotate: function(o, angle) {
angle = (angle + 360) % 360;
this.toPolar(o);
this.y += toRad(angle);
var p = point.fromPolar(this.x, this.y, o);
this.x = p.x;
this.y = p.y;
return this;
},
// Move point on line starting from ref ending at me by
// distance distance.
move: function(ref, distance) {
var theta = toRad(point(ref).theta(this));
return this.offset(cos(theta) * distance, -sin(theta) * distance);
},
// Returns change in angle from my previous position (-dx, -dy) to my new position
// relative to ref point.
changeInAngle: function(dx, dy, ref) {
// Revert the translation and measure the change in angle around x-axis.
return point(this).offset(-dx, -dy).theta(ref) - this.theta(ref);
},
equals: function(p) {
return this.x === p.x && this.y === p.y;
}
};
// Alternative constructor, from polar coordinates.
// @param {number} r Distance.
// @param {number} angle Angle in radians.
// @param {point} [optional] o Origin.
point.fromPolar = function(r, angle, o) {
o = (o && point(o)) || point(0,0);
var x = abs(r * cos(angle));
var y = abs(r * sin(angle));
var deg = normalizeAngle(toDeg(angle));
if (deg < 90) y = -y;
else if (deg < 180) { x = -x; y = -y; }
else if (deg < 270) x = -x;
return point(o.x + x, o.y + y);
};
// Create a point with random coordinates that fall into the range `[x1, x2]` and `[y1, y2]`.
point.random = function(x1, x2, y1, y2) {
return point(floor(random() * (x2 - x1 + 1) + x1), floor(random() * (y2 - y1 + 1) + y1));
};
// Line.
// -----
function line(p1, p2) {
if (!(this instanceof line))
return new line(p1, p2);
this.start = point(p1);
this.end = point(p2);
}
line.prototype = {
toString: function() {
return this.start.toString() + ' ' + this.end.toString();
},
// @return {double} length of the line
length: function() {
return sqrt(this.squaredLength());
},
// @return {integer} length without sqrt
// @note for applications where the exact length is not necessary (e.g. compare only)
squaredLength: function() {
var x0 = this.start.x;
var y0 = this.start.y;
var x1 = this.end.x;
var y1 = this.end.y;
return (x0 -= x1)*x0 + (y0 -= y1)*y0;
},
// @return {point} my midpoint
midpoint: function() {
return point((this.start.x + this.end.x) / 2,
(this.start.y + this.end.y) / 2);
},
// @return {point} Point where I'm intersecting l.
// @see Squeak Smalltalk, LineSegment>>intersectionWith:
intersection: function(l) {
var pt1Dir = point(this.end.x - this.start.x, this.end.y - this.start.y);
var pt2Dir = point(l.end.x - l.start.x, l.end.y - l.start.y);
var det = (pt1Dir.x * pt2Dir.y) - (pt1Dir.y * pt2Dir.x);
var deltaPt = point(l.start.x - this.start.x, l.start.y - this.start.y);
var alpha = (deltaPt.x * pt2Dir.y) - (deltaPt.y * pt2Dir.x);
var beta = (deltaPt.x * pt1Dir.y) - (deltaPt.y * pt1Dir.x);
if (det === 0 ||
alpha * det < 0 ||
beta * det < 0) {
// No intersection found.
return null;
}
if (det > 0){
if (alpha > det || beta > det){
return null;
}
} else {
if (alpha < det || beta < det){
return null;
}
}
return point(this.start.x + (alpha * pt1Dir.x / det),
this.start.y + (alpha * pt1Dir.y / det));
}
};
// Rectangle.
// ----------
function rect(x, y, w, h) {
if (!(this instanceof rect))
return new rect(x, y, w, h);
if (y === undefined) {
y = x.y;
w = x.width;
h = x.height;
x = x.x;
}
this.x = x;
this.y = y;
this.width = w;
this.height = h;
}
rect.prototype = {
toString: function() {
return this.origin().toString() + ' ' + this.corner().toString();
},
origin: function() {
return point(this.x, this.y);
},
corner: function() {
return point(this.x + this.width, this.y + this.height);
},
topRight: function() {
return point(this.x + this.width, this.y);
},
bottomLeft: function() {
return point(this.x, this.y + this.height);
},
center: function() {
return point(this.x + this.width/2, this.y + this.height/2);
},
// @return {boolean} true if rectangles intersect
intersect: function(r) {
var myOrigin = this.origin();
var myCorner = this.corner();
var rOrigin = r.origin();
var rCorner = r.corner();
if (rCorner.x <= myOrigin.x ||
rCorner.y <= myOrigin.y ||
rOrigin.x >= myCorner.x ||
rOrigin.y >= myCorner.y) return false;
return true;
},
// @return {string} (left|right|top|bottom) side which is nearest to point
// @see Squeak Smalltalk, Rectangle>>sideNearestTo:
sideNearestToPoint: function(p) {
p = point(p);
var distToLeft = p.x - this.x;
var distToRight = (this.x + this.width) - p.x;
var distToTop = p.y - this.y;
var distToBottom = (this.y + this.height) - p.y;
var closest = distToLeft;
var side = 'left';
if (distToRight < closest) {
closest = distToRight;
side = 'right';
}
if (distToTop < closest) {
closest = distToTop;
side = 'top';
}
if (distToBottom < closest) {
closest = distToBottom;
side = 'bottom';
}
return side;
},
// @return {bool} true if point p is insight me
containsPoint: function(p) {
p = point(p);
if (p.x > this.x && p.x < this.x + this.width &&
p.y > this.y && p.y < this.y + this.height) {
return true;
}
return false;
},
// @return {point} a point on my boundary nearest to p
// @see Squeak Smalltalk, Rectangle>>pointNearestTo:
pointNearestToPoint: function(p) {
p = point(p);
if (this.containsPoint(p)) {
var side = this.sideNearestToPoint(p);
switch (side){
case "right": return point(this.x + this.width, p.y);
case "left": return point(this.x, p.y);
case "bottom": return point(p.x, this.y + this.height);
case "top": return point(p.x, this.y);
}
}
return p.adhereToRect(this);
},
// Find point on my boundary where line starting
// from my center ending in point p intersects me.
// @param {number} angle If angle is specified, intersection with rotated rectangle is computed.
intersectionWithLineFromCenterToPoint: function(p, angle) {
p = point(p);
var center = point(this.x + this.width/2, this.y + this.height/2);
var result;
if (angle) p.rotate(center, angle);
// (clockwise, starting from the top side)
var sides = [
line(this.origin(), this.topRight()),
line(this.topRight(), this.corner()),
line(this.corner(), this.bottomLeft()),
line(this.bottomLeft(), this.origin())
];
var connector = line(center, p);
for (var i = sides.length - 1; i >= 0; --i){
var intersection = sides[i].intersection(connector);
if (intersection !== null){
result = intersection;
break;
}
}
if (result && angle) result.rotate(center, -angle);
return result;
},
// Move and expand me.
// @param r {rectangle} representing deltas
moveAndExpand: function(r) {
this.x += r.x;
this.y += r.y;
this.width += r.width;
this.height += r.height;
return this;
},
round: function(decimals) {
this.x = decimals ? this.x.toFixed(decimals) : round(this.x);
this.y = decimals ? this.y.toFixed(decimals) : round(this.y);
this.width = decimals ? this.width.toFixed(decimals) : round(this.width);
this.height = decimals ? this.height.toFixed(decimals) : round(this.height);
return this;
}
};
// Ellipse.
// --------
function ellipse(c, a, b) {
if (!(this instanceof ellipse))
return new ellipse(c, a, b);
c = point(c);
this.x = c.x;
this.y = c.y;
this.a = a;
this.b = b;
}
ellipse.prototype = {
toString: function() {
return point(this.x, this.y).toString() + ' ' + this.a + ' ' + this.b;
},
bbox: function() {
return rect(this.x - this.a, this.y - this.b, 2*this.a, 2*this.b);
},
// Find point on me where line from my center to
// point p intersects my boundary.
// @param {number} angle If angle is specified, intersection with rotated ellipse is computed.
intersectionWithLineFromCenterToPoint: function(p, angle) {
p = point(p);
if (angle) p.rotate(point(this.x, this.y), angle);
var dx = p.x - this.x;
var dy = p.y - this.y;
var result;
if (dx === 0) {
result = this.bbox().pointNearestToPoint(p);
if (angle) return result.rotate(point(this.x, this.y), -angle);
return result;
}
var m = dy / dx;
var mSquared = m * m;
var aSquared = this.a * this.a;
var bSquared = this.b * this.b;
var x = sqrt(1 / ((1 / aSquared) + (mSquared / bSquared)));
x = dx < 0 ? -x : x;
var y = m * x;
result = point(this.x + x, this.y + y);
if (angle) return result.rotate(point(this.x, this.y), -angle);
return result;
}
};
// Bezier curve.
// -------------
var bezier = {
// Cubic Bezier curve path through points.
// Ported from C# implementation by Oleg V. Polikarpotchkin and Peter Lee (http://www.codeproject.com/KB/graphics/BezierSpline.aspx).
// @param {array} points Array of points through which the smooth line will go.
// @return {array} SVG Path commands as an array
curveThroughPoints: function(points) {
var controlPoints = this.getCurveControlPoints(points);
var path = ['M', points[0].x, points[0].y];
for (var i = 0; i < controlPoints[0].length; i++) {
path.push('C', controlPoints[0][i].x, controlPoints[0][i].y, controlPoints[1][i].x, controlPoints[1][i].y, points[i+1].x, points[i+1].y);
}
return path;
},
// Get open-ended Bezier Spline Control Points.
// @param knots Input Knot Bezier spline points (At least two points!).
// @param firstControlPoints Output First Control points. Array of knots.length - 1 length.
// @param secondControlPoints Output Second Control points. Array of knots.length - 1 length.
getCurveControlPoints: function(knots) {
var firstControlPoints = [];
var secondControlPoints = [];
var n = knots.length - 1;
var i;
// Special case: Bezier curve should be a straight line.
if (n == 1) {
// 3P1 = 2P0 + P3
firstControlPoints[0] = point((2 * knots[0].x + knots[1].x) / 3,
(2 * knots[0].y + knots[1].y) / 3);
// P2 = 2P1 – P0
secondControlPoints[0] = point(2 * firstControlPoints[0].x - knots[0].x,
2 * firstControlPoints[0].y - knots[0].y);
return [firstControlPoints, secondControlPoints];
}
// Calculate first Bezier control points.
// Right hand side vector.
var rhs = [];
// Set right hand side X values.
for (i = 1; i < n - 1; i++) {
rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x;
}
rhs[0] = knots[0].x + 2 * knots[1].x;
rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0;
// Get first control points X-values.
var x = this.getFirstControlPoints(rhs);
// Set right hand side Y values.
for (i = 1; i < n - 1; ++i) {
rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y;
}
rhs[0] = knots[0].y + 2 * knots[1].y;
rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0;
// Get first control points Y-values.
var y = this.getFirstControlPoints(rhs);
// Fill output arrays.
for (i = 0; i < n; i++) {
// First control point.
firstControlPoints.push(point(x[i], y[i]));
// Second control point.
if (i < n - 1) {
secondControlPoints.push(point(2 * knots [i + 1].x - x[i + 1],
2 * knots[i + 1].y - y[i + 1]));
} else {
secondControlPoints.push(point((knots[n].x + x[n - 1]) / 2,
(knots[n].y + y[n - 1]) / 2));
}
}
return [firstControlPoints, secondControlPoints];
},
// Solves a tridiagonal system for one of coordinates (x or y) of first Bezier control points.
// @param rhs Right hand side vector.
// @return Solution vector.
getFirstControlPoints: function(rhs) {
var n = rhs.length;
// `x` is a solution vector.
var x = [];
var tmp = [];
var b = 2.0;
x[0] = rhs[0] / b;
// Decomposition and forward substitution.
for (var i = 1; i < n; i++) {
tmp[i] = 1 / b;
b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
x[i] = (rhs[i] - x[i - 1]) / b;
}
for (i = 1; i < n; i++) {
// Backsubstitution.
x[n - i - 1] -= tmp[n - i] * x[n - i];
}
return x;
}
};
return {
toDeg: toDeg,
toRad: toRad,
snapToGrid: snapToGrid,
normalizeAngle: normalizeAngle,
point: point,
line: line,
rect: rect,
ellipse: ellipse,
bezier: bezier
}
}));
// JointJS, the JavaScript diagramming library.
// (c) 2011-2013 client IO
if (typeof exports === 'object') {
var joint = {
dia: {
Link: require('./joint.dia.link').Link,
Element: require('./joint.dia.element').Element
},
shapes: require('../plugins/shapes')
};
var Backbone = require('backbone');
var _ = require('lodash');
var g = require('./geometry').g;
}
joint.dia.GraphCells = Backbone.Collection.extend({
initialize: function() {
// Backbone automatically doesn't trigger re-sort if models attributes are changed later when
// they're already in the collection. Therefore, we're triggering sort manually here.
this.on('change:z', this.sort, this);
},
model: function(attrs, options) {
if (attrs.type === 'link') {
return new joint.dia.Link(attrs, options);
}
var module = attrs.type.split('.')[0];
var entity = attrs.type.split('.')[1];
if (joint.shapes[module] && joint.shapes[module][entity]) {
return new joint.shapes[module][entity](attrs, options);
}
return new joint.dia.Element(attrs, options);
},
// `comparator` makes it easy to sort cells based on their `z` index.
comparator: function(model) {
return model.get('z') || 0;
},
// Get all inbound and outbound links connected to the cell `model`.
getConnectedLinks: function(model, opt) {
opt = opt || {};
if (_.isUndefined(opt.inbound) && _.isUndefined(opt.outbound)) {
opt.inbound = opt.outbound = true;
}
var links = [];
this.each(function(cell) {
var source = cell.get('source');
var target = cell.get('target');
if (source && source.id === model.id && opt.outbound) {
links.push(cell);
}
if (target && target.id === model.id && opt.inbound) {
links.push(cell);
}
});
return links;
}
});
joint.dia.Graph = Backbone.Model.extend({
initialize: function() {
this.set('cells', new joint.dia.GraphCells);
// Make all the events fired in the `cells` collection available.
// to the outside world.
this.get('cells').on('all', this.trigger, this);
this.get('cells').on('remove', this.removeCell, this);
},
toJSON: function() {
// Backbone does not recursively call `toJSON()` on attributes that are themselves models/collections.
// It just clones the attributes. Therefore, we must call `toJSON()` on the cells collection explicitely.
var json = Backbone.Model.prototype.toJSON.apply(this, arguments);
json.cells = this.get('cells').toJSON();
return json;
},
fromJSON: function(json) {
if (!json.cells) {
throw new Error('Graph JSON must contain cells array.');
}
var attrs = json;
// Cells are the only attribute that is being set differently, using `cells.add()`.
var cells = json.cells;
delete attrs.cells;
this.set(attrs);
this.resetCells(cells);
},
clear: function() {
this.get('cells').remove(this.get('cells').models);
},
_prepareCell: function(cell) {
if (cell instanceof Backbone.Model && _.isUndefined(cell.get('z'))) {
cell.set('z', this.get('cells').length, { silent: true });
} else if (_.isUndefined(cell.z)) {
cell.z = this.get('cells').length;
}
return cell;
},
addCell: function(cell, options) {
if (_.isArray(cell)) {
return this.addCells(cell, options);
}
this.get('cells').add(this._prepareCell(cell), options || {});
return this;
},
addCells: function(cells, options) {
_.each(cells, function(cell) { this.addCell(cell, options); }, this);
return this;
},
// When adding a lot of cells, it is much more efficient to
// reset the entire cells collection in one go.
// Useful for bulk operations and optimizations.
resetCells: function(cells) {
this.get('cells').reset(_.map(cells, this._prepareCell, this));
return this;
},
removeCell: function(cell, collection, options) {
// Applications might provide a `disconnectLinks` option set to `true` in order to
// disconnect links when a cell is removed rather then removing them. The default
// is to remove all the associated links.
if (options && options.disconnectLinks) {
this.disconnectLinks(cell);
} else {
this.removeLinks(cell);
}
// Silently remove the cell from the cells collection. Silently, because
// `joint.dia.Cell.prototype.remove` already triggers the `remove` event which is
// then propagated to the graph model. If we didn't remove the cell silently, two `remove` events
// would be triggered on the graph model.
this.get('cells').remove(cell, { silent: true });
},
// Get a cell by `id`.
getCell: function(id) {
return this.get('cells').get(id);
},
getElements: function() {
return this.get('cells').filter(function(cell) {
return cell instanceof joint.dia.Element;
});
},
getLinks: function() {
return this.get('cells').filter(function(cell) {
return cell instanceof joint.dia.Link;
});
},
// Get all inbound and outbound links connected to the cell `model`.
getConnectedLinks: function(model, opt) {
return this.get('cells').getConnectedLinks(model, opt);
},
getNeighbors: function(el) {
var links = this.getConnectedLinks(el);
var neighbors = [];
var cells = this.get('cells');
_.each(links, function(link) {
var source = link.get('source');
var target = link.get('target');
// Discard if it is a point.
if (!source.x) {
var sourceElement = cells.get(source.id);
if (sourceElement !== el) {
neighbors.push(sourceElement);
}
}
if (!target.x) {
var targetElement = cells.get(target.id);
if (targetElement !== el) {
neighbors.push(targetElement);
}
}
});
return neighbors;
},
// Disconnect links connected to the cell `model`.
disconnectLinks: function(model) {
_.each(this.getConnectedLinks(model), function(link) {
link.set(link.get('source').id === model.id ? 'source' : 'target', g.point(0, 0));
});
},
// Remove links connected to the cell `model` completely.
removeLinks: function(model) {
_.invoke(this.getConnectedLinks(model), 'remove');
},
// Find all views at given point
findModelsFromPoint: function(p) {
return _.filter(this.getElements(), function(el) {
return el.getBBox().containsPoint(p);
});
},
// Find all views in given area
findModelsInArea: function(r) {
return _.filter(this.getElements(), function(el) {
return el.getBBox().intersect(r);
});
}
});
if (typeof exports === 'object') {
module.exports.Graph = joint.dia.Graph;
}
// JointJS.
// (c) 2011-2013 client IO
if (typeof exports === 'object') {
var joint = {
util: require('./core').util,
dia: {
Link: require('./joint.dia.link').Link
}
};
var Backbone = require('backbone');
var _ = require('lodash');
}
// joint.dia.Cell base model.
// --------------------------
joint.dia.Cell = Backbone.Model.extend({
// This is the same as Backbone.Model with the only difference that is uses _.merge
// instead of just _.extend. The reason is that we want to mixin attributes set in upper classes.
constructor: function(attributes, options) {
var defaults;
var attrs = attributes || {};
this.cid = _.uniqueId('c');
this.attributes = {};
if (options && options.collection) this.collection = options.collection;
if (options && options.parse) attrs = this.parse(attrs, options) || {};
if (defaults = _.result(this, 'defaults')) {
//<custom code>
// Replaced the call to _.defaults with _.merge.
attrs = _.merge({}, defaults, attrs);
//</custom code>
}
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
},
toJSON: function() {
var defaultAttrs = this.constructor.prototype.defaults.attrs || {};
var attrs = this.attributes.attrs;
var finalAttrs = {};
// Loop through all the attributes and
// omit the default attributes as they are implicitly reconstructable by the cell 'type'.
_.each(attrs, function(attr, selector) {
var defaultAttr = defaultAttrs[selector];
_.each(attr, function(value, name) {
// attr is mainly flat though it might have one more level (consider the `style` attribute).
// Check if the `value` is object and if yes, go one level deep.
if (_.isObject(value) && !_.isArray(value)) {
_.each(value, function(value2, name2) {
if (!defaultAttr || !defaultAttr[name] || !_.isEqual(defaultAttr[name][name2], value2)) {
finalAttrs[selector] = finalAttrs[selector] || {};
(finalAttrs[selector][name] || (finalAttrs[selector][name] = {}))[name2] = value2;
}
});
} else if (!defaultAttr || !_.isEqual(defaultAttr[name], value)) {
// `value` is not an object, default attribute for such a selector does not exist
// or it is different than the attribute value set on the model.
finalAttrs[selector] = finalAttrs[selector] || {};
finalAttrs[selector][name] = value;
}
});
});
var attributes = _.cloneDeep(_.omit(this.attributes, 'attrs'));
//var attributes = JSON.parse(JSON.stringify(_.omit(this.attributes, 'attrs')));
attributes.attrs = finalAttrs;
return attributes;
},
initialize: function(options) {
if (!options || !options.id) {
this.set('id', joint.util.uuid(), { silent: true });
}
this._transitionIds = {};
// Collect ports defined in `attrs` and keep collecting whenever `attrs` object changes.
this.processPorts();
this.on('change:attrs', this.processPorts, this);
},
processPorts: function() {
// Whenever `attrs` changes, we extract ports from the `attrs` object and store it
// in a more accessible way. Also, if any port got removed and there were links that had `target`/`source`
// set to that port, we remove those links as well (to follow the same behaviour as
// with a removed element).
var previousPorts = this.ports;
// Collect ports from the `attrs` object.
var ports = {};
_.each(this.get('attrs'), function(attrs, selector) {
if (attrs.port) {
// `port` can either be directly an `id` or an object containing an `id` (and potentially other data).
if (!_.isUndefined(attrs.port.id)) {
ports[attrs.port.id] = attrs.port;
} else {
ports[attrs.port] = { id: attrs.port };
}
}
});
// Collect ports that have been removed (compared to the previous ports) - if any.
// Use hash table for quick lookup.
var removedPorts = {};
_.each(previousPorts, function(port, id) {
if (!ports[id]) removedPorts[id] = true;
});
// Remove all the incoming/outgoing links that have source/target port set to any of the removed ports.
if (this.collection && !_.isEmpty(removedPorts)) {
var inboundLinks = this.collection.getConnectedLinks(this, { inbound: true });
_.each(inboundLinks, function(link) {
if (removedPorts[link.get('target').port]) link.remove();
});
var outboundLinks = this.collection.getConnectedLinks(this, { outbound: true });
_.each(outboundLinks, function(link) {
if (removedPorts[link.get('source').port]) link.remove();
});
}
// Update the `ports` object.
this.ports = ports;
},
remove: function(options) {
var collection = this.collection;
if (collection) {
collection.trigger('batch:start');
}
// First, unembed this cell from its parent cell if there is one.
var parentCellId = this.get('parent');
if (parentCellId) {
var parentCell = this.collection && this.collection.get(parentCellId);
parentCell.unembed(this);
}
_.invoke(this.getEmbeddedCells(), 'remove', options);
this.trigger('remove', this, this.collection, options);
if (collection) {
collection.trigger('batch:stop');
}
},
toFront: function() {
if (this.collection) {
this.set('z', (this.collection.last().get('z') || 0) + 1);
}
},
toBack: function() {
if (this.collection) {
this.set('z', (this.collection.first().get('z') || 0) - 1);
}
},
embed: function(cell) {
if (this.get('parent') == cell.id) {
throw new Error('Recursive embedding not allowed.');
} else {
this.trigger('batch:start');
cell.set('parent', this.id);
this.set('embeds', _.uniq((this.get('embeds') || []).concat([cell.id])));
this.trigger('batch:stop');
}
},
unembed: function(cell) {
this.trigger('batch:start');
var cellId = cell.id;
cell.unset('parent');
this.set('embeds', _.without(this.get('embeds'), cellId));
this.trigger('batch:stop');
},
getEmbeddedCells: function() {
// Cell models can only be retrieved when this element is part of a collection.
// There is no way this element knows about other cells otherwise.
// This also means that calling e.g. `translate()` on an element with embeds before
// adding it to a graph does not translate its embeds.
if (this.collection) {
return _.map(this.get('embeds') || [], function(cellId) {
return this.collection.get(cellId);
}, this);
}
return [];
},
clone: function(opt) {
opt = opt || {};
var clone = Backbone.Model.prototype.clone.apply(this, arguments);
// We don't want the clone to have the same ID as the original.
clone.set('id', joint.util.uuid(), { silent: true });
clone.set('embeds', '');
if (!opt.deep) return clone;
// The rest of the `clone()` method deals with embeds. If `deep` option is set to `true`,
// the return value is an array of all the embedded clones created.
var embeds = this.getEmbeddedCells();
var clones = [clone];
// This mapping stores cloned links under the `id`s of they originals.
// This prevents cloning a link more then once. Consider a link 'self loop' for example.
var linkCloneMapping = {};
_.each(embeds, function(embed) {
var embedClones = embed.clone({ deep: true });
// Embed the first clone returned from `clone({ deep: true })` above. The first
// cell is always the clone of the cell that called the `clone()` method, i.e. clone of `embed` in this case.
clone.embed(embedClones[0]);
_.each(embedClones, function(embedClone) {
clones.push(embedClone);
// Skip links. Inbound/outbound links are not relevant for them.
if (embedClone instanceof joint.dia.Link) {
return;
}
// Collect all inbound links, clone them (if not done already) and set their target to the `embedClone.id`.
var inboundLinks = this.collection.getConnectedLinks(embed, { inbound: true });
_.each(inboundLinks, function(link) {
var linkClone = linkCloneMapping[link.id] || link.clone();
// Make sure we don't clone a link more then once.
linkCloneMapping[link.id] = linkClone;
var target = _.clone(linkClone.get('target'));
target.id = embedClone.id;
linkClone.set('target', target);
});
// Collect all inbound links, clone them (if not done already) and set their source to the `embedClone.id`.
var outboundLinks = this.collection.getConnectedLinks(embed, { outbound: true });
_.each(outboundLinks, function(link) {
var linkClone = linkCloneMapping[link.id] || link.clone();
// Make sure we don't clone a link more then once.
linkCloneMapping[link.id] = linkClone;
var source = _.clone(linkClone.get('source'));
source.id = embedClone.id;
linkClone.set('source', source);
});
}, this);
}, this);
// Add link clones to the array of all the new clones.
clones = clones.concat(_.values(linkCloneMapping));
return clones;
},
// A convenient way to set nested attributes.
attr: function(attrs, value, opt) {
var currentAttrs = this.get('attrs');
var delim = '/';
if (_.isString(attrs)) {
// Get/set an attribute by a special path syntax that delimits
// nested objects by the colon character.
if (value) {
var attr = {};
joint.util.setByPath(attr, attrs, value, delim);
return this.set('attrs', _.merge({}, currentAttrs, attr), opt);
} else {
return joint.util.getByPath(currentAttrs, attrs, delim);
}
}
return this.set('attrs', _.merge({}, currentAttrs, attrs), value);
},
transition: function(path, value, opt, delim) {
delim = delim || '/';
var defaults = {
duration: 100,
delay: 10,
timingFunction: joint.util.timing.linear,
valueFunction: joint.util.interpolate.number
};
opt = _.extend(defaults, opt);
var pathArray = path.split(delim);
var property = pathArray[0];
var isPropertyNested = pathArray.length > 1;
var firstFrameTime = 0;
var interpolatingFunction;
var setter = _.bind(function(runtime) {
var id, progress, propertyValue, status;
firstFrameTime = firstFrameTime || runtime;
runtime -= firstFrameTime;
progress = runtime / opt.duration;
if (progress < 1) {
this._transitionIds[path] = id = joint.util.nextFrame(setter);
} else {
progress = 1;
delete this._transitionIds[path];
}
propertyValue = interpolatingFunction(opt.timingFunction(progress));
if (isPropertyNested) {
var nestedPropertyValue = joint.util.setByPath({}, path, propertyValue, delim)[property];
propertyValue = _.merge({}, this.get(property), nestedPropertyValue);
}
opt.transitionId = id;
this.set(property, propertyValue, opt);
if (!id) this.trigger('transition:end', this, path);
}, this);
var initiator =_.bind(function(callback) {
this.stopTransitions(path);
interpolatingFunction = opt.valueFunction(joint.util.getByPath(this.attributes, path, delim), value);
this._transitionIds[path] = joint.util.nextFrame(callback);
this.trigger('transition:start', this, path);
}, this);
return _.delay(initiator, opt.delay, setter);
},
getTransitions: function() {
return _.keys(this._transitionIds);
},
stopTransitions: function(path, delim) {
delim = delim || '/';
var pathArray = path && path.split(delim);
_(this._transitionIds).keys().filter(pathArray && function(key) {
return _.isEqual(pathArray, key.split(delim).slice(0, pathArray.length));
}).each(function(key) {
joint.util.cancelFrame(this._transitionIds[key]);
delete this._transitionIds[key];
this.trigger('transition:end', this, key);
}, this);
}
});
// joint.dia.CellView base view and controller.
// --------------------------------------------
// This is the base view and controller for `joint.dia.ElementView` and `joint.dia.LinkView`.
joint.dia.CellView = Backbone.View.extend({
tagName: 'g',
attributes: function() {
return { 'model-id': this.model.id }
},
initialize: function() {
_.bindAll(this, 'remove', 'update');
// Store reference to this to the <g> DOM element so that the view is accessible through the DOM tree.
this.$el.data('view', this);
this.listenTo(this.model, 'remove', this.remove);
this.listenTo(this.model, 'change:attrs', this.update);
},
_configure: function(options) {
// Make sure a global unique id is assigned to this view. Store this id also to the properties object.
// The global unique id makes sure that the same view can be rendered on e.g. different machines and
// still be associated to the same object among all those clients. This is necessary for real-time
// collaboration mechanism.
options.id = options.id || joint.util.guid(this);
Backbone.View.prototype._configure.apply(this, arguments);
},
// Override the Backbone `_ensureElement()` method in order to create a `<g>` node that wraps
// all the nodes of the Cell view.
_ensureElement: function() {
var el;
if (!this.el) {
var attrs = _.extend({ id: this.id }, _.result(this, 'attributes'));
if (this.className) attrs['class'] = _.result(this, 'className');
el = V(_.result(this, 'tagName'), attrs).node;
} else {
el = _.result(this, 'el')
}
this.setElement(el, false);
},
findBySelector: function(selector) {
// These are either descendants of `this.$el` of `this.$el` itself.
// `.` is a special selector used to select the wrapping `<g>` element.
var $selected = selector === '.' ? this.$el : this.$el.find(selector);
return $selected;
},
notify: function(evt) {
if (this.paper) {
var args = Array.prototype.slice.call(arguments, 1);
// Trigger the event on both the element itself and also on the paper.
this.trigger.apply(this, [evt].concat(args));
// Paper event handlers receive the view object as the first argument.
this.paper.trigger.apply(this.paper, [evt, this].concat(args));
}
},
getStrokeBBox: function(el) {
// Return a bounding box rectangle that takes into account stroke.
// Note that this is a naive and ad-hoc implementation that does not
// works only in certain cases and should be replaced as soon as browsers will
// start supporting the getStrokeBBox() SVG method.
// @TODO any better solution is very welcome!
var isMagnet = !!el;
el = el || this.el;
var bbox = V(el).bbox(false, this.paper.viewport);
var strokeWidth;
if (isMagnet) {
strokeWidth = V(el).attr('stroke-width');
} else {
strokeWidth = this.model.attr('rect/stroke-width') || this.model.attr('circle/stroke-width') || this.model.attr('ellipse/stroke-width') || this.model.attr('path/stroke-width');
}
strokeWidth = parseFloat(strokeWidth) || 0;
return g.rect(bbox).moveAndExpand({ x: -strokeWidth/2, y: -strokeWidth/2, width: strokeWidth, height: strokeWidth });
},
getBBox: function() {
return V(this.el).bbox();
},
highlight: function(el) {
el = !el ? this.el : this.$(el)[0] || this.el;
var attrClass = V(el).attr('class') || '';
if (!/\bhighlighted\b/.exec(attrClass)) V(el).attr('class', attrClass.trim() + ' highlighted');
},
unhighlight: function(el) {
el = !el ? this.el : this.$(el)[0] || this.el;
V(el).attr('class', (V(el).attr('class') || '').replace(/\bhighlighted\b/, '').trim());
},
// Find the closest element that has the `magnet` attribute set to `true`. If there was not such
// an element found, return the root element of the cell view.
findMagnet: function(el) {
var $el = this.$(el);
if ($el.length === 0 || $el[0] === this.el) {
// If the overall cell has set `magnet === false`, then return `undefined` to
// announce there is no magnet found for this cell.
// This is especially useful to set on cells that have 'ports'. In this case,
// only the ports have set `magnet === true` and the overall element has `magnet === false`.
var attrs = this.model.get('attrs') || {};
if (attrs['.'] && attrs['.']['magnet'] === false) {
return undefined;
}
return this.el;
}
if ($el.attr('magnet')) {
return $el[0];
}
return this.findMagnet($el.parent());
},
// `selector` is a CSS selector or `'.'`. `filter` must be in the special JointJS filter format:
// `{ name: <name of the filter>, args: { <arguments>, ... }`.
// An example is: `{ filter: { name: 'blur', args: { radius: 5 } } }`.
applyFilter: function(selector, filter) {
var $selected = this.findBySelector(selector);
// Generate a hash code from the stringified filter definition. This gives us
// a unique filter ID for different definitions.
var filterId = filter.name + this.paper.svg.id + joint.util.hashCode(JSON.stringify(filter));
// If the filter already exists in the document,
// we're done and we can just use it (reference it using `url()`).
// If not, create one.
if (!this.paper.svg.getElementById(filterId)) {
var filterSVGString = joint.util.filter[filter.name] && joint.util.filter[filter.name](filter.args || {});
if (!filterSVGString) {
throw new Error('Non-existing filter ' + filter.name);
}
var filterElement = V(filterSVGString);
filterElement.attr('filterUnits', 'userSpaceOnUse');
filterElement.node.id = filterId;
V(this.paper.svg).defs().append(filterElement);
}
$selected.each(function() {
V(this).attr('filter', 'url(#' + filterId + ')');
});
},
// `selector` is a CSS selector or `'.'`. `attr` is either a `'fill'` or `'stroke'`.
// `gradient` must be in the special JointJS gradient format:
// `{ type: <linearGradient|radialGradient>, stops: [ { offset: <offset>, color: <color> }, ... ]`.
// An example is: `{ fill: { type: 'linearGradient', stops: [ { offset: '10%', color: 'green' }, { offset: '50%', color: 'blue' } ] } }`.
applyGradient: function(selector, attr, gradient) {
var $selected = this.findBySelector(selector);
// Generate a hash code from the stringified filter definition. This gives us
// a unique filter ID for different definitions.
var gradientId = gradient.type + this.paper.svg.id + joint.util.hashCode(JSON.stringify(gradient));
// If the gradient already exists in the document,
// we're done and we can just use it (reference it using `url()`).
// If not, create one.
if (!this.paper.svg.getElementById(gradientId)) {
var gradientSVGString = [
'<' + gradient.type + '>',
_.map(gradient.stops, function(stop) {
return '<stop offset="' + stop.offset + '" stop-color="' + stop.color + '" stop-opacity="' + (_.isFinite(stop.opacity) ? stop.opacity : 1) + '" />'
}).join(''),
'</' + gradient.type + '>'
].join('');
var gradientElement = V(gradientSVGString);
if (gradient.attrs) { gradientElement.attr(gradient.attrs); }
gradientElement.node.id = gradientId;
V(this.paper.svg).defs().append(gradientElement);
}
$selected.each(function() {
V(this).attr(attr, 'url(#' + gradientId + ')');
});
},
// Construct a unique selector for the `el` element within this view.
// `selector` is being collected through the recursive call. No value for `selector` is expected when using this method.
getSelector: function(el, selector) {
if (el === this.el) {
return selector;
}
var index = $(el).index();
selector = el.tagName + ':nth-child(' + (index + 1) + ')' + ' ' + (selector || '');
return this.getSelector($(el).parent()[0], selector + ' ');
},
// Interaction. The controller part.
// ---------------------------------
// Interaction is handled by the paper and delegated to the view in interest.
// `x` & `y` parameters passed to these functions represent the coordinates already snapped to the paper grid.
// If necessary, real coordinates can be obtained from the `evt` event object.
// These functions are supposed to be overriden by the views that inherit from `joint.dia.Cell`,
// i.e. `joint.dia.Element` and `joint.dia.Link`.
pointerdblclick: function(evt, x, y) {
this.notify('cell:pointerdblclick', evt, x, y);
},
pointerdown: function(evt, x, y) {
if (this.model.collection) {
this.model.trigger('batch:start');
this._collection = this.model.collection;
}
this.notify('cell:pointerdown', evt, x, y);
},
pointermove: function(evt, x, y) {
this.notify('cell:pointermove', evt, x, y);
},
pointerup: function(evt, x, y) {
this.notify('cell:pointerup', evt, x, y);
if (this._collection) {
// we don't want to trigger event on model as model doesn't
// need to be member of collection anymore (remove)
this._collection.trigger('batch:stop');
delete this._collection;
}
}
});
if (typeof exports === 'object') {
module.exports.Cell = joint.dia.Cell;
module.exports.CellView = joint.dia.CellView;
}
// JointJS library.
// (c) 2011-2013 client IO
if (typeof exports === 'object') {
var joint = {
util: require('./core').util,
dia: {
Cell: require('./joint.dia.cell').Cell,
CellView: require('./joint.dia.cell').CellView
}
};
var Backbone = require('backbone');
var _ = require('lodash');
}
// joint.dia.Element base model.
// -----------------------------
joint.dia.Element = joint.dia.Cell.extend({
defaults: {
position: { x: 0, y: 0 },
size: { width: 1, height: 1 },
angle: 0
},
position: function(x, y) {
this.set('position', { x: x, y: y });
},
translate: function(tx, ty, opt) {
ty = ty || 0;
if (tx === 0 && ty === 0) {
// Like nothing has happened.
return this;
}
var position = this.get('position') || { x: 0, y: 0 };
var translatedPosition = { x: position.x + tx || 0, y: position.y + ty || 0 };
if (opt && opt.transition) {
if (!_.isObject(opt.transition)) opt.transition = {};
this.transition('position', translatedPosition, _.extend({}, opt.transition, {
valueFunction: joint.util.interpolate.object
}));
} else {
this.set('position', translatedPosition, opt);
// Recursively call `translate()` on all the embeds cells.
_.invoke(this.getEmbeddedCells(), 'translate', tx, ty, opt);
}
return this;
},
resize: function(width, height) {
this.trigger('batch:start');
this.set('size', { width: width, height: height });
this.trigger('batch:stop');
return this;
},
rotate: function(angle, absolute) {
return this.set('angle', absolute ? angle : ((this.get('angle') || 0) + angle) % 360);
},
getBBox: function() {
var position = this.get('position');
var size = this.get('size');
return g.rect(position.x, position.y, size.width, size.height);
}
});
// joint.dia.Element base view and controller.
// -------------------------------------------
joint.dia.ElementView = joint.dia.CellView.extend({
className: function() {
return 'element ' + this.model.get('type').split('.').join(' ');
},
initialize: function() {
_.bindAll(this, 'translate', 'resize', 'rotate');
joint.dia.CellView.prototype.initialize.apply(this, arguments);
this.listenTo(this.model, 'change:position', this.translate);
this.listenTo(this.model, 'change:size', this.resize);
this.listenTo(this.model, 'change:angle', this.rotate);
},
// Default is to process the `attrs` object and set attributes on subelements based on the selectors.
update: function(cell, renderingOnlyAttrs) {
var allAttrs = this.model.get('attrs');
var rotatable = V(this.$('.rotatable')[0]);
if (rotatable) {
var rotation = rotatable.attr('transform');
rotatable.attr('transform', '');
}
var relativelyPositioned = [];
// Special attributes are treated by JointJS, not by SVG.
var specialAttributes = ['style', 'text', 'html', 'ref-x', 'ref-y', 'ref-dx', 'ref-dy', 'ref', 'x-alignment', 'y-alignment', 'port'];
_.each(renderingOnlyAttrs || allAttrs, function(attrs, selector) {
// Elements that should be updated.
var $selected = this.findBySelector(selector);
// No element matched by the `selector` was found. We're done then.
if ($selected.length === 0) return;
// Special attributes are treated by JointJS, not by SVG.
var specialAttributes = ['style', 'text', 'html', 'ref-x', 'ref-y', 'ref-dx', 'ref-dy', 'ref', 'x-alignment', 'y-alignment', 'port'];
// If the `filter` attribute is an object, it is in the special JointJS filter format and so
// it becomes a special attribute and is treated separately.
if (_.isObject(attrs.filter)) {
specialAttributes.push('filter');
this.applyFilter(selector, attrs.filter);
}
// If the `fill` or `stroke` attribute is an object, it is in the special JointJS gradient format and so
// it becomes a special attribute and is treated separately.
if (_.isObject(attrs.fill)) {
specialAttributes.push('fill');
this.applyGradient(selector, 'fill', attrs.fill);
}
if (_.isObject(attrs.stroke)) {
specialAttributes.push('stroke');
this.applyGradient(selector, 'stroke', attrs.stroke);
}
// Set regular attributes on the `$selected` subelement. Note that we cannot use the jQuery attr()
// method as some of the attributes might be namespaced (e.g. xlink:href) which fails with jQuery attr().
var finalAttributes = _.omit(attrs, specialAttributes);
$selected.each(function() {
V(this).attr(finalAttributes);
});
// `port` attribute contains the `id` of the port that the underlying magnet represents.
if (attrs.port) {
$selected.attr('port', _.isUndefined(attrs.port.id) ? attrs.port : attrs.port.id);
}
// `style` attribute is special in the sense that it sets the CSS style of the subelement.
if (attrs.style) {
$selected.css(attrs.style);
}
// Make special case for `text` attribute. So that we can set text content of the `<text>` element
// via the `attrs` object as well.
if (!_.isUndefined(attrs.text)) {
$selected.each(function() {
V(this).text(attrs.text + '');
});
}
if (!_.isUndefined(attrs.html)) {
$selected.each(function() {
$(this).html(attrs.html + '');
});
}
// Special `ref-x` and `ref-y` attributes make it possible to set both absolute or
// relative positioning of subelements.
if (!_.isUndefined(attrs['ref-x']) ||
!_.isUndefined(attrs['ref-y']) ||
!_.isUndefined(attrs['ref-dx']) ||
!_.isUndefined(attrs['ref-dy']) ||
!_.isUndefined(attrs['x-alignment']) ||
!_.isUndefined(attrs['y-alignment'])
) {
relativelyPositioned.push($selected);
}
}, this);
// We don't want the sub elements to affect the bounding box of the root element when
// positioning the sub elements relatively to the bounding box.
//_.invoke(relativelyPositioned, 'hide');
//_.invoke(relativelyPositioned, 'show');
// Note that we're using the bounding box without transformation because we are already inside
// a transformed coordinate system.
var bbox = this.el.getBBox();
renderingOnlyAttrs = renderingOnlyAttrs || {};
_.each(relativelyPositioned, function($el) {
// if there was a special attribute affecting the position amongst renderingOnlyAttributes
// we have to merge it with rest of the element's attributes as they are necessary
// to update the position relatively (i.e `ref`)
var renderingOnlyElAttrs = renderingOnlyAttrs[$el.selector];
var elAttrs = renderingOnlyElAttrs
? _.merge({}, allAttrs[$el.selector], renderingOnlyElAttrs)
: allAttrs[$el.selector];
this.positionRelative($el, bbox, elAttrs);
}, this);
if (rotatable) {
rotatable.attr('transform', rotation || '');
}
},
positionRelative: function($el, bbox, elAttrs) {
var ref = elAttrs['ref'];
var refX = parseFloat(elAttrs['ref-x']);
var refY = parseFloat(elAttrs['ref-y']);
var refDx = parseFloat(elAttrs['ref-dx']);
var refDy = parseFloat(elAttrs['ref-dy']);
var yAlignment = elAttrs['y-alignment'];
var xAlignment = elAttrs['x-alignment'];
// `ref` is the selector of the reference element. If no `ref` is passed, reference
// element is the root element.
var isScalable = _.contains(_.pluck(_.pluck($el.parents('g'), 'className'), 'baseVal'), 'scalable');
if (ref) {
// Get the bounding box of the reference element relative to the root `<g>` element.
bbox = V(this.findBySelector(ref)[0]).bbox(false, this.el);
}
var vel = V($el[0]);
// Remove the previous translate() from the transform attribute and translate the element
// relative to the root bounding box following the `ref-x` and `ref-y` attributes.
if (vel.attr('transform')) {
vel.attr('transform', vel.attr('transform').replace(/translate\([^)]*\)/g, '') || '');
}
function isDefined(x) {
return _.isNumber(x) && !_.isNaN(x);
}
// The final translation of the subelement.
var tx = 0;
var ty = 0;
// `ref-dx` and `ref-dy` define the offset of the subelement relative to the right and/or bottom
// coordinate of the reference element.
if (isDefined(refDx)) {
if (isScalable) {
// Compensate for the scale grid in case the elemnt is in the scalable group.
var scale = V(this.$('.scalable')[0]).scale();
tx = bbox.x + bbox.width + refDx / scale.sx;
} else {
tx = bbox.x + bbox.width + refDx;
}
}
if (isDefined(refDy)) {
if (isScalable) {
// Compensate for the scale grid in case the elemnt is in the scalable group.
var scale = V(this.$('.scalable')[0]).scale();
ty = bbox.y + bbox.height + refDy / scale.sy;
} else {
ty = bbox.y + bbox.height + refDy;
}
}
// if `refX` is in [0, 1] then `refX` is a fraction of bounding box width
// if `refX` is < 0 then `refX`'s absolute values is the right coordinate of the bounding box
// otherwise, `refX` is the left coordinate of the bounding box
// Analogical rules apply for `refY`.
if (isDefined(refX)) {
if (refX > 0 && refX < 1) {
tx = bbox.x + bbox.width * refX;
} else if (isScalable) {
// Compensate for the scale grid in case the elemnt is in the scalable group.
var scale = V(this.$('.scalable')[0]).scale();
tx = bbox.x + refX / scale.sx;
} else {
tx = bbox.x + refX;
}
}
if (isDefined(refY)) {
if (refY > 0 && refY < 1) {
ty = bbox.y + bbox.height * refY;
} else if (isScalable) {
// Compensate for the scale grid in case the elemnt is in the scalable group.
var scale = V(this.$('.scalable')[0]).scale();
ty = bbox.y + refY / scale.sy;
} else {
ty = bbox.y + refY;
}
}
var velbbox = vel.bbox(false, this.paper.viewport);
// `y-alignment` when set to `middle` causes centering of the subelement around its new y coordinate.
if (yAlignment === 'middle') {
ty -= velbbox.height/2;
} else if (isDefined(yAlignment)) {
ty += (yAlignment > 0 && yAlignment < 1) ? velbbox.height * yAlignment : yAlignment;
}
// `x-alignment` when set to `middle` causes centering of the subelement around its new x coordinate.
if (xAlignment === 'middle') {
tx -= velbbox.width/2;
} else if (isDefined(xAlignment)) {
tx += (xAlignment > 0 && xAlignment < 1) ? velbbox.width * xAlignment : xAlignment;
}
vel.translate(tx, ty);
},
// `prototype.markup` is rendered by default. Set the `markup` attribute on the model if the
// default markup is not desirable.
render: function() {
var markup = this.model.markup || this.model.get('markup');
if (markup) {
var nodes = V(markup);
V(this.el).append(nodes);
} else {
throw new Error('properties.markup is missing while the default render() implementation is used.');
}
this.update();
this.resize();
this.rotate();
this.translate();
return this;
},
// Scale the whole `<g>` group. Note the difference between `scale()` and `resize()` here.
// `resize()` doesn't scale the whole `<g>` group but rather adjusts the `box.sx`/`box.sy` only.
// `update()` is then responsible for scaling only those elements that have the `follow-scale`
// attribute set to `true`. This is desirable in elements that have e.g. a `<text>` subelement
// that is not supposed to be scaled together with a surrounding `<rect>` element that IS supposed
// be be scaled.
scale: function(sx, sy) {
// TODO: take into account the origin coordinates `ox` and `oy`.
V(this.el).scale(sx, sy);
},
resize: function() {
var size = this.model.get('size') || { width: 1, height: 1 };
var angle = this.model.get('angle') || 0;
var scalable = V(this.$('.scalable')[0]);
if (!scalable) {
// If there is no scalable elements, than there is nothing to resize.
return;
}
var scalableBbox = scalable.bbox(true);
scalable.attr('transform', 'scale(' + (size.width / scalableBbox.width) + ',' + (size.height / scalableBbox.height) + ')');
// Now the interesting part. The goal is to be able to store the object geometry via just `x`, `y`, `angle`, `width` and `height`
// Order of transformations is significant but we want to reconstruct the object always in the order:
// resize(), rotate(), translate() no matter of how the object was transformed. For that to work,
// we must adjust the `x` and `y` coordinates of the object whenever we resize it (because the origin of the
// rotation changes). The new `x` and `y` coordinates are computed by canceling the previous rotation
// around the center of the resized object (which is a different origin then the origin of the previous rotation)
// and getting the top-left corner of the resulting object. Then we clean up the rotation back to what it originally was.
// Cancel the rotation but now around a different origin, which is the center of the scaled object.
var rotatable = V(this.$('.rotatable')[0]);
var rotation = rotatable && rotatable.attr('transform');
if (rotation && rotation !== 'null') {
rotatable.attr('transform', rotation + ' rotate(' + (-angle) + ',' + (size.width/2) + ',' + (size.height/2) + ')');
var rotatableBbox = scalable.bbox(false, this.paper.viewport);
// Store new x, y and perform rotate() again against the new rotation origin.
this.model.set('position', { x: rotatableBbox.x, y: rotatableBbox.y });
this.rotate();
}
// Update must always be called on non-rotated element. Otherwise, relative positioning
// would work with wrong (rotated) bounding boxes.
this.update();
},
translate: function(model, changes, opt) {
var position = this.model.get('position') || { x: 0, y: 0 };
V(this.el).attr('transform', 'translate(' + position.x + ',' + position.y + ')');
},
rotate: function() {
var rotatable = V(this.$('.rotatable')[0]);
if (!rotatable) {
// If there is no rotatable elements, then there is nothing to rotate.
return;
}
var angle = this.model.get('angle') || 0;
var size = this.model.get('size') || { width: 1, height: 1 };
var ox = size.width/2;
var oy = size.height/2;
rotatable.attr('transform', 'rotate(' + angle + ',' + ox + ',' + oy + ')');
},
// Interaction. The controller part.
// ---------------------------------
pointerdown: function(evt, x, y) {
if ( // target is a valid magnet start linking
evt.target.getAttribute('magnet') &&
this.paper.options.validateMagnet.call(this.paper, this, evt.target)
) {
this.model.trigger('batch:start');
var link = this.paper.getDefaultLink(this, evt.target);
link.set({
source: {
id: this.model.id,
selector: this.getSelector(evt.target),
port: $(evt.target).attr('port')
},
target: { x: x, y: y }
});
this.paper.model.addCell(link);
this._linkView = this.paper.findViewByModel(link);
this._linkView.startArrowheadMove('target');
} else {
this._dx = x;
this._dy = y;
joint.dia.CellView.prototype.pointerdown.apply(this, arguments);
}
},
pointermove: function(evt, x, y) {
if (this._linkView) {
// let the linkview deal with this event
this._linkView.pointermove(evt, x, y);
} else {
var grid = this.paper.options.gridSize;
if (this.options.interactive !== false) {
var position = this.model.get('position');
// Make sure the new element's position always snaps to the current grid after
// translate as the previous one could be calculated with a different grid size.
this.model.translate(
g.snapToGrid(position.x, grid) - position.x + g.snapToGrid(x - this._dx, grid),
g.snapToGrid(position.y, grid) - position.y + g.snapToGrid(y - this._dy, grid)
);
}
this._dx = g.snapToGrid(x, grid);
this._dy = g.snapToGrid(y, grid);
joint.dia.CellView.prototype.pointermove.apply(this, arguments);
}
},
pointerup: function(evt, x, y) {
if (this._linkView) {
// let the linkview deal with this event
this._linkView.pointerup(evt, x, y);
delete this._linkView;
this.model.trigger('batch:stop');
} else {
joint.dia.CellView.prototype.pointerup.apply(this, arguments);
}
}
});
if (typeof exports === 'object') {
module.exports.Element = joint.dia.Element;
module.exports.ElementView = joint.dia.ElementView;
}
// JointJS diagramming library.
// (c) 2011-2013 client IO
if (typeof exports === 'object') {
var joint = {
dia: {
Cell: require('./joint.dia.cell').Cell,
CellView: require('./joint.dia.cell').CellView
}
};
var Backbone = require('backbone');
var _ = require('lodash');
var g = require('./geometry').g;
}
// joint.dia.Link base model.
// --------------------------
joint.dia.Link = joint.dia.Cell.extend({
// The default markup for links.
markup: [
'<path class="connection" stroke="black"/>',
'<path class="marker-source" fill="black" stroke="black" />',
'<path class="marker-target" fill="black" stroke="black" />',
'<path class="connection-wrap"/>',
'<g class="labels"/>',
'<g class="marker-vertices"/>',
'<g class="marker-arrowheads"/>',
'<g class="link-tools"/>'
].join(''),
labelMarkup: [
'<g class="label">',
'<rect />',
'<text />',
'</g>'
].join(''),
toolMarkup: [
'<g class="link-tool">',
'<g class="tool-remove" event="remove">',
'<circle r="11" />',
'<path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/>',
'<title>Remove link.</title>',
'</g>',
'<g class="tool-options" event="link:options">',
'<circle r="11" transform="translate(25)"/>',
'<path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/>',
'<title>Link options.</title>',
'</g>',
'</g>'
].join(''),
// The default markup for showing/removing vertices. These elements are the children of the .marker-vertices element (see `this.markup`).
// Only .marker-vertex and .marker-vertex-remove element have special meaning. The former is used for
// dragging vertices (changin their position). The latter is used for removing vertices.
vertexMarkup: [
'<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">',
'<circle class="marker-vertex" idx="<%= idx %>" r="10" />',
'<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>',
'<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">',
'<title>Remove vertex.</title>',
'</path>',
'</g>'
].join(''),
arrowheadMarkup: [
'<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">',
'<path class="marker-arrowhead" end="<%= end %>" d="M 26 0 L 0 13 L 26 26 z" />',
'</g>'
].join(''),
defaults: {
type: 'link'
},
disconnect: function() {
return this.set({ source: g.point(0, 0), target: g.point(0, 0) });
},
// A convenient way to set labels. Currently set values will be mixined with `value` if used as a setter.
label: function(idx, value) {
idx = idx || 0;
var labels = this.get('labels');
// Is it a getter?
if (arguments.length === 0 || arguments.length === 1) {
return labels && labels[idx];
}
var newValue = _.merge({}, labels[idx], value);
var newLabels = labels.slice();
newLabels[idx] = newValue;
return this.set({ labels: newLabels });
}
});
// joint.dia.Link base view and controller.
// ----------------------------------------
joint.dia.LinkView = joint.dia.CellView.extend({
className: 'link',
options: {
shortLinkLength: 100
},
initialize: function() {
joint.dia.CellView.prototype.initialize.apply(this, arguments);
// create method shortcuts
this.watchSource = this._createWatcher('source');
this.watchTarget = this._createWatcher('target');
// `_.labelCache` is a mapping of indexes of labels in the `this.get('labels')` array to
// `<g class="label">` nodes wrapped by Vectorizer. This allows for quick access to the
// nodes in `updateLabelPosition()` in order to update the label positions.
this._labelCache = {};
// bind events
this.startListening();
},
startListening: function() {
this.listenTo(this.model, 'change:markup', this.render);
this.listenTo(this.model, 'change:smooth change:manhattan', this.update);
this.listenTo(this.model, 'change:toolMarkup', function() {
this.renderTools().updateToolsPosition();
});
this.listenTo(this.model, 'change:labels change:labelMarkup', function() {
this.renderLabels().updateLabelPositions();
});
this.listenTo(this.model, 'change:vertices change:vertexMarkup', function() {
this.renderVertexMarkers().update();
});
this.listenTo(this.model, 'change:source', function(cell, source) {
this.watchSource(cell, source).update();
});
this.listenTo(this.model, 'change:target', function(cell, target) {
this.watchTarget(cell, target).update();
});
},
// Rendering
//----------
render: function() {
this.$el.empty();
// A special markup can be given in the `properties.markup` property. This might be handy
// if e.g. arrowhead markers should be `<image>` elements or any other element than `<path>`s.
// `.connection`, `.connection-wrap`, `.marker-source` and `.marker-target` selectors
// of elements with special meaning though. Therefore, those classes should be preserved in any
// special markup passed in `properties.markup`.
var children = V(this.model.get('markup') || this.model.markup);
// custom markup may contain only one children
if (!_.isArray(children)) children = [children];
// Cache all children elements for quicker access.
this._V = {} // vectorized markup;
_.each(children, function(child) {
var c = child.attr('class');
c && (this._V[$.camelCase(c)] = child);
}, this);
// Only the connection path is mandatory
if (!this._V.connection) throw new Error('link: no connection path in the markup');
// partial rendering
this.renderLabels();
this.renderTools();
this.renderVertexMarkers();
this.renderArrowheadMarkers();
V(this.el).append(children);
// start watching the ends of the link for changes
this.watchSource(this.model, this.model.get('source'))
.watchTarget(this.model, this.model.get('target'))
.update();
return this;
},
renderLabels: function() {
if (!this._V.labels) return this;
this._labelCache = {};
var $labels = $(this._V.labels.node).empty();
var labels = this.model.get('labels') || [];
if (!labels.length) return this;
var labelTemplate = _.template(this.model.get('labelMarkup') || this.model.labelMarkup);
// This is a prepared instance of a vectorized SVGDOM node for the label element resulting from
// compilation of the labelTemplate. The purpose is that all labels will just `clone()` this
// node to create a duplicate.
var labelNodeInstance = V(labelTemplate());
_.each(labels, function(label, idx) {
var labelNode = labelNodeInstance.clone().node;
// Cache label nodes so that the `updateLabels()` can just update the label node positions.
this._labelCache[idx] = V(labelNode);
var $text = $(labelNode).find('text');
var $rect = $(labelNode).find('rect');
// Text attributes with the default `text-anchor` set.
var textAttributes = _.extend({ 'text-anchor': 'middle' }, joint.util.getByPath(label, 'attrs/text', '/'));
$text.attr(_.omit(textAttributes, 'text'));
if (!_.isUndefined(textAttributes.text)) {
V($text[0]).text(textAttributes.text + '');
}
// Note that we first need to append the `<text>` element to the DOM in order to
// get its bounding box.
$labels.append(labelNode);
// `y-alignment` - center the text element around its y coordinate.
var textBbox = V($text[0]).bbox(true, $labels[0]);
V($text[0]).translate(0, -textBbox.height/2);
// Add default values.
var rectAttributes = _.extend({
fill: 'white',
rx: 3,
ry: 3
}, joint.util.getByPath(label, 'attrs/rect', '/'));
$rect.attr(_.extend(rectAttributes, {
x: textBbox.x,
y: textBbox.y - textBbox.height/2, // Take into account the y-alignment translation.
width: textBbox.width,
height: textBbox.height
}));
}, this);
return this;
},
renderTools: function() {
if (!this._V.linkTools) return this;
// Tools are a group of clickable elements that manipulate the whole link.
// A good example of this is the remove tool that removes the whole link.
// Tools appear after hovering the link close to the `source` element/point of the link
// but are offset a bit so that they don't cover the `marker-arrowhead`.
var $tools = $(this._V.linkTools.node).empty();
var toolTemplate = _.template(this.model.get('toolMarkup') || this.model.toolMarkup);
var tool = V(toolTemplate());
$tools.append(tool.node);
// Cache the tool node so that the `updateToolsPosition()` can update the tool position quickly.
this._toolCache = tool;
return this;
},
renderVertexMarkers: function() {
if (!this._V.markerVertices) return this;
var $markerVertices = $(this._V.markerVertices.node).empty();
// A special markup can be given in the `properties.vertexMarkup` property. This might be handy
// if default styling (elements) are not desired. This makes it possible to use any
// SVG elements for .marker-vertex and .marker-vertex-remove tools.
var markupTemplate = _.template(this.model.get('vertexMarkup') || this.model.vertexMarkup);
_.each(this.model.get('vertices'), function(vertex, idx) {
$markerVertices.append(V(markupTemplate(_.extend({ idx: idx }, vertex))).node);
});
return this;
},
renderArrowheadMarkers: function() {
// Custom markups might not have arrowhead markers. Therefore, jump of this function immediately if that's the case.
if (!this._V.markerArrowheads) return this;
var $markerArrowheads = $(this._V.markerArrowheads.node);
$markerArrowheads.empty();
// A special markup can be given in the `properties.vertexMarkup` property. This might be handy
// if default styling (elements) are not desired. This makes it possible to use any
// SVG elements for .marker-vertex and .marker-vertex-remove tools.
var markupTemplate = _.template(this.model.get('arrowheadMarkup') || this.model.arrowheadMarkup);
this._sourceArrowhead = V(markupTemplate({ end: 'source' }));
this._targetArrowhead = V(markupTemplate({ end: 'target' }));
$markerArrowheads.append(this._sourceArrowhead.node, this._targetArrowhead.node);
return this;
},
// Updating
//---------
// Default is to process the `attrs` object and set attributes on subelements based on the selectors.
update: function() {
// Update attributes.
_.each(this.model.get('attrs'), function(attrs, selector) {
// If the `filter` attribute is an object, it is in the special JointJS filter format and so
// it becomes a special attribute and is treated separately.
if (_.isObject(attrs.filter)) {
this.findBySelector(selector).attr(_.omit(attrs, 'filter'));
this.applyFilter(selector, attrs.filter);
} else {
this.findBySelector(selector).attr(attrs);
}
}, this);
var vertices = this.model.get('vertices');
if (this.model.get('manhattan')) {
// If manhattan routing is enabled, find new vertices so that the link is orthogonally routed.
vertices = this.findManhattanRoute(vertices);
}
this._firstVertex = _.first(vertices);
this._sourcePoint = this.getConnectionPoint(
'source',
this.model.get('source'),
this._firstVertex || this.model.get('target')).round();
this._lastVertex = _.last(vertices);
this._targetPoint = this.getConnectionPoint(
'target',
this.model.get('target'),
this._lastVertex || this._sourcePoint
);
// Make the markers "point" to their sticky points being auto-oriented towards
// `targetPosition`/`sourcePosition`. And do so only if there is a markup for them.
if (this._V.markerSource) {
this._V.markerSource.translateAndAutoOrient(
this._sourcePoint,
this._firstVertex || this._targetPoint,
this.paper.viewport
);
}
if (this._V.markerTarget) {
this._V.markerTarget.translateAndAutoOrient(
this._targetPoint,
this._lastVertex || this._sourcePoint,
this.paper.viewport
);
}
var pathData = this.getPathData(vertices);
// The markup needs to contain a `.connection`
this._V.connection.attr('d', pathData);
this._V.connectionWrap && this._V.connectionWrap.attr('d', pathData);
//partials updates
this.updateLabelPositions();
this.updateToolsPosition();
this.updateArrowheadMarkers();
return this;
},
updateLabelPositions: function() {
if (!this._V.labels) return this;
// This method assumes all the label nodes are stored in the `this._labelCache` hash table
// by their indexes in the `this.get('labels')` array. This is done in the `renderLabels()` method.
var labels = this.model.get('labels') || [];
if (!labels.length) return this;
var connectionElement = this._V.connection.node;
var connectionLength = connectionElement.getTotalLength();
_.each(labels, function(label, idx) {
var position = label.position;
position = (position > connectionLength) ? connectionLength : position; // sanity check
position = (position < 0) ? connectionLength + position : position;
position = position > 1 ? position : connectionLength * position;
var labelCoordinates = connectionElement.getPointAtLength(position);
this._labelCache[idx].attr('transform', 'translate(' + labelCoordinates.x + ', ' + labelCoordinates.y + ')');
}, this);
return this;
},
updateToolsPosition: function() {
if (!this._V.linkTools) return this;
// Move the tools a bit to the target position but don't cover the `sourceArrowhead` marker.
// Note that the offset is hardcoded here. The offset should be always
// more than the `this.$('.marker-arrowhead[end="source"]')[0].bbox().width` but looking
// this up all the time would be slow.
var scale = '';
var offset = 40;
// If the link is too short, make the tools half the size and the offset twice as low.
if (this.getConnectionLength() < this.options.shortLinkLength) {
scale = 'scale(.5)';
offset /= 2;
}
var toolPosition = this.getPointAtLength(offset);
this._toolCache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale);
return this;
},
updateArrowheadMarkers: function() {
if (!this._V.markerArrowheads) return this;
// getting bbox of an element with `display="none"` in IE9 ends up with access violation
if ($.css(this._V.markerArrowheads.node, 'display') === 'none') return this;
var sx = this.getConnectionLength() < this.options.shortLinkLength ? .5 : 1
this._sourceArrowhead.scale(sx);
this._targetArrowhead.scale(sx);
// Make the markers "point" to their sticky points being auto-oriented towards `targetPosition`/`sourcePosition`.
this._sourceArrowhead.translateAndAutoOrient(
this._sourcePoint,
this._firstVertex || this._targetPoint,
this.paper.viewport
);
this._targetArrowhead.translateAndAutoOrient(
this._targetPoint,
this._lastVertex || this._sourcePoint,
this.paper.viewport
);
return this;
},
_createWatcher: function(endType) {
function watchEnd(link, end) {
end = end || {};
var previousEnd = link.previous(endType) || {};
if (this._isModel(previousEnd)) {
this.stopListening(this.paper.getModelById(previousEnd.id), 'change');
}
if (this._isModel(end)) {
this.listenTo(this.paper.getModelById(end.id), 'change', function() {
this._cacheEndBbox(endType, end).update();
});
}
return this._cacheEndBbox(endType, end);
}
return watchEnd;
},
_cacheEndBbox: function(endType, end) {
var cacheBbox = '_' + endType + 'Bbox';
if (this._isModel(end)) {
var selector = this._makeSelector(end);
var view = this.paper.findViewByModel(end.id);
var magnetElement = this.paper.viewport.querySelector(selector);
this[cacheBbox] = view.getStrokeBBox(magnetElement);
} else {
// the link end is a point ~ rect 1x1
this[cacheBbox] = {
width: 1, height: 1,
x: end.x, y: end.y
};
}
return this;
},
removeVertex: function(idx) {
var vertices = _.clone(this.model.get('vertices'));
if (vertices && vertices.length) {
vertices.splice(idx, 1);
this.model.set('vertices', vertices);
}
return this;
},
// This method ads a new vertex to the `vertices` array of `.connection`. This method
// uses a heuristic to find the index at which the new `vertex` should be placed at assuming
// the new vertex is somewhere on the path.
addVertex: function(vertex) {
this.model.set('attrs', this.model.get('attrs') || {});
var attrs = this.model.get('attrs');
// As it is very hard to find a correct index of the newly created vertex,
// a little heuristics is taking place here.
// The heuristics checks if length of the newly created
// path is lot more than length of the old path. If this is the case,
// new vertex was probably put into a wrong index.
// Try to put it into another index and repeat the heuristics again.
var vertices = (this.model.get('vertices') || []).slice();
// Store the original vertices for a later revert if needed.
var originalVertices = vertices.slice();
// A `<path>` element used to compute the length of the path during heuristics.
var path = this._V.connection.node.cloneNode(false);
// Length of the original path.
var originalPathLength = path.getTotalLength();
// Current path length.
var pathLength;
// Tolerance determines the highest possible difference between the length
// of the old and new path. The number has been chosen heuristically.
var pathLengthTolerance = 20;
// Total number of vertices including source and target points.
var idx = vertices.length + 1;
// Loop through all possible indexes and check if the difference between
// path lengths changes significantly. If not, the found index is
// most probably the right one.
while (idx--) {
vertices.splice(idx, 0, vertex);
V(path).attr('d', this.getPathData(vertices));
pathLength = path.getTotalLength();
// Check if the path lengths changed significantly.
if (pathLength - originalPathLength > pathLengthTolerance) {
// Revert vertices to the original array. The path length has changed too much
// so that the index was not found yet.
vertices = originalVertices.slice();
} else {
break;
}
}
this.model.set('vertices', vertices);
// In manhattan routing, if there are no vertices, the path length changes significantly
// with the first vertex added. Shall we check vertices.length === 0? at beginning of addVertex()
// in order to avoid the temporary path construction and other operations?
return Math.max(idx, 0);
},
// Return the `d` attribute value of the `<path>` element representing the link between `source` and `target`.
getPathData: function(vertices) {
var sourcePoint = g.point(this._sourcePoint);
var targetPoint = g.point(this._targetPoint);
// Move the source point by the width of the marker taking into account its scale around x-axis.
// Note that scale is the only transform that makes sense to be set in `.marker-source` attributes object
// as all other transforms (translate/rotate) will be replaced by the `translateAndAutoOrient()` function.
if (this._V.markerSource) {
this._markerSourceBbox = this._markerSourceBbox || this._V.markerSource.bbox(true);
sourcePoint.move(
this._firstVertex || targetPoint,
this._markerSourceBbox.width * -this._V.markerSource.scale().sx
);
}
if (this._V.markerTarget) {
this._markerTargetBbox = this._markerTargetBbox || this._V.markerTarget.bbox(true);
targetPoint.move(
this._lastVertex || sourcePoint,
this._markerTargetBbox.width * -this._V.markerTarget.scale().sx
);
}
var d;
if (this.model.get('smooth')) {
if (vertices && vertices.length) {
d = g.bezier.curveThroughPoints([sourcePoint].concat(vertices || []).concat([targetPoint]));
} else {
// if we have no vertices use a default cubic bezier curve, cubic bezier requires two control points.
// the two control points are both defined with X as mid way between the source and target points.
// sourceControlPoint Y is equal to sourcePoint Y and targetControlPointY being equal to targetPointY.
// handle situation were sourcePointX is greater or less then targetPointX.
var controlPointX = (sourcePoint.x < targetPoint.x)
? targetPoint.x - ((targetPoint.x - sourcePoint.x) / 2)
: sourcePoint.x - ((sourcePoint.x - targetPoint.x) / 2);
d = ['M', sourcePoint.x, sourcePoint.y, 'C', controlPointX, sourcePoint.y, controlPointX, targetPoint.y, targetPoint.x, targetPoint.y];
}
} else {
// Construct the `d` attribute of the `<path>` element.
d = ['M', sourcePoint.x, sourcePoint.y];
_.each(vertices, function(vertex) {
d.push(vertex.x, vertex.y);
});
d.push(targetPoint.x, targetPoint.y);
}
return d.join(' ');
},
// Find a point that is the start of the connection.
// If `selectorOrPoint` is a point, then we're done and that point is the start of the connection.
// If the `selectorOrPoint` is an element however, we need to know a reference point (or element)
// that the link leads to in order to determine the start of the connection on the original element.
getConnectionPoint: function(end, selectorOrPoint, referenceSelectorOrPoint) {
var spot;
if (this._isPoint(selectorOrPoint)) {
// If the source is a point, we don't need a reference point to find the sticky point of connection.
spot = g.point(selectorOrPoint);
} else {
// If the source is an element, we need to find a point on the element boundary that is closest
// to the reference point (or reference element).
// Get the bounding box of the spot relative to the paper viewport. This is necessary
// in order to follow paper viewport transformations (scale/rotate).
// `_sourceBbox` and `_targetBbox` come both from `_cacheEndBbox` method, they exist
// since first render and are automatically updated
var spotBbox = end === 'source' ? this._sourceBbox : this._targetBbox;
var reference;
if (this._isPoint(referenceSelectorOrPoint)) {
// Reference was passed as a point, therefore, we're ready to find the sticky point of connection on the source element.
reference = g.point(referenceSelectorOrPoint);
} else {
// Reference was passed as an element, therefore we need to find a point on the reference
// element boundary closest to the source element.
// Get the bounding box of the spot relative to the paper viewport. This is necessary
// in order to follow paper viewport transformations (scale/rotate).
var referenceBbox = end === 'source' ? this._targetBbox : this._sourceBbox;
reference = g.rect(referenceBbox).intersectionWithLineFromCenterToPoint(g.rect(spotBbox).center());
reference = reference || g.rect(referenceBbox).center();
}
// If `perpendicularLinks` flag is set on the paper and there are vertices
// on the link, then try to find a connection point that makes the link perpendicular
// even though the link won't point to the center of the targeted object.
if (this.paper.options.perpendicularLinks) {
var horizontalLineRect = g.rect(0, reference.y, this.paper.options.width, 1);
var verticalLineRect = g.rect(reference.x, 0, 1, this.paper.options.height);
var nearestSide;
if (horizontalLineRect.intersect(g.rect(spotBbox))) {
nearestSide = g.rect(spotBbox).sideNearestToPoint(reference);
switch (nearestSide) {
case 'left':
spot = g.point(spotBbox.x, reference.y);
break;
case 'right':
spot = g.point(spotBbox.x + spotBbox.width, reference.y);
break;
default:
spot = g.rect(spotBbox).center();
break;
}
} else if (verticalLineRect.intersect(g.rect(spotBbox))) {
nearestSide = g.rect(spotBbox).sideNearestToPoint(reference);
switch (nearestSide) {
case 'top':
spot = g.point(reference.x, spotBbox.y);
break;
case 'bottom':
spot = g.point(reference.x, spotBbox.y + spotBbox.height);
break;
default:
spot = g.rect(spotBbox).center();
break;
}
} else {
// If there is no intersection horizontally or vertically with the object bounding box,
// then we fall back to the regular situation finding straight line (not perpendicular)
// between the object and the reference point.
spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference);
spot = spot || g.rect(spotBbox).center();
}
} else {
spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference);
spot = spot || g.rect(spotBbox).center();
}
}
return spot;
},
_isModel: function(end) {
return end && end.id;
},
_isPoint: function(end) {
return !this._isModel(end);
},
_makeSelector: function(end) {
var selector = '[model-id="' + end.id + '"]';
// `port` has a higher precendence over `selector`. This is because the selector to the magnet
// might change while the name of the port can stay the same.
if (end.port) {
selector += ' [port="' + end.port + '"]';
} else if (end.selector) {
selector += ' ' + end.selector;
}
return selector;
},
// Return points that one needs to draw a connection through in order to have a manhattan link routing from
// source to target going through `vertices`.
findManhattanRoute: function(vertices) {
vertices = (vertices || []).slice();
var manhattanVertices = [];
// Return the direction that one would have to take traveling from `p1` to `p2`.
// This function assumes the line between `p1` and `p2` is orthogonal.
function direction(p1, p2) {
if (p1.y < p2.y && p1.x === p2.x) {
return 'down';
} else if (p1.y > p2.y && p1.x === p2.x) {
return 'up';
} else if (p1.x < p2.x && p1.y === p2.y) {
return 'right';
}
return 'left';
}
function bestDirection(p1, p2, preferredDirection) {
var directions;
// This branching determines possible directions that one can take to travel
// from `p1` to `p2`.
if (p1.x < p2.x) {
if (p1.y > p2.y) { directions = ['up', 'right']; }
else if (p1.y < p2.y) { directions = ['down', 'right']; }
else { directions = ['right']; }
} else if (p1.x > p2.x) {
if (p1.y > p2.y) { directions = ['up', 'left']; }
else if (p1.y < p2.y) { directions = ['down', 'left']; }
else { directions = ['left']; }
} else {
if (p1.y > p2.y) { directions = ['up']; }
else { directions = ['down']; }
}
if (_.contains(directions, preferredDirection)) {
return preferredDirection;
}
var direction = _.first(directions);
// Should the direction be the exact opposite of the preferred direction,
// try another one if such direction exists.
switch (preferredDirection) {
case 'down': if (direction === 'up') return _.last(directions); break;
case 'up': if (direction === 'down') return _.last(directions); break;
case 'left': if (direction === 'right') return _.last(directions); break;
case 'right': if (direction === 'left') return _.last(directions); break;
}
return direction;
}
// Find a vertex in between the vertices `p1` and `p2` so that the route between those vertices
// is orthogonal. Prefer going the direction determined by `preferredDirection`.
function findMiddleVertex(p1, p2, preferredDirection) {
var direction = bestDirection(p1, p2, preferredDirection);
if (direction === 'down' || direction === 'up') {
return { x: p1.x, y: p2.y, d: direction };
}
return { x: p2.x, y: p1.y, d: direction };
}
var sourceCenter = g.rect(this._sourceBbox).center();
var targetCenter = g.rect(this._targetBbox).center();
vertices.unshift(sourceCenter);
vertices.push(targetCenter);
var manhattanVertex;
var lastManhattanVertex;
var vertex;
var nextVertex;
// For all the pairs of link model vertices...
for (var i = 0; i < vertices.length - 1; i++) {
vertex = vertices[i];
nextVertex = vertices[i + 1];
lastManhattanVertex = _.last(manhattanVertices);
if (i > 0) {
// Push all the link vertices to the manhattan route.
manhattanVertex = vertex;
// Determine a direction between the last vertex and the new one.
// Therefore, each vertex contains the `d` property describing the direction that one
// would have to take to travel to that vertex.
manhattanVertex.d = lastManhattanVertex ? direction(lastManhattanVertex, vertex) : 'top';
manhattanVertices.push(manhattanVertex);
lastManhattanVertex = manhattanVertex;
}
// Make sure that we don't create a vertex that would go the opposite direction then that of the
// previous one. Othwerwise, a 'spike' segment would be created which is not desirable.
// Find a dummy vertex to keep the link orthogonal. Preferably, take the same direction
// as the previous one.
var d = lastManhattanVertex && lastManhattanVertex.d;
manhattanVertex = findMiddleVertex(vertex, nextVertex, d);
// Do not add a new vertex that is the same as one of the vertices already added.
if (!g.point(manhattanVertex).equals(g.point(vertex)) && !g.point(manhattanVertex).equals(g.point(nextVertex))) {
manhattanVertices.push(manhattanVertex);
}
}
return manhattanVertices;
},
// Public API
// ----------
getConnectionLength: function() {
return this._V.connection.node.getTotalLength();
},
getPointAtLength: function(length) {
return this._V.connection.node.getPointAtLength(length);
},
// Interaction. The controller part.
// ---------------------------------
_beforeArrowheadMove: function() {
this.model.trigger('batch:start');
this._z = this.model.get('z');
this.model.set('z', Number.MAX_VALUE);
// Let the pointer propagate throught the link view elements so that
// the `evt.target` is another element under the pointer, not the link itself.
this.el.style.pointerEvents = 'none';
},
_afterArrowheadMove: function() {
if (this._z) {
this.model.set('z', this._z);
delete this._z;
}
// Put `pointer-events` back to its original value. See `startArrowheadMove()` for explanation.
// Value `auto` doesn't work in IE9. We force to use `visiblePainted` instead.
// See `https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events`.
this.el.style.pointerEvents = 'visiblePainted';
this.model.trigger('batch:stop');
},
_createValidateConnectionArgs: function(arrowhead) {
// It makes sure the arguments for validateConnection have the following form:
// (source view, source magnet, target view, target magnet and link view)
var args = [];
args[4] = arrowhead;
args[5] = this;
var oppositeArrowhead, i = 0, j = 0;
if (arrowhead === 'source') {
i = 2;
oppositeArrowhead = 'target';
} else {
j = 2;
oppositeArrowhead = 'source';
}
var end = this.model.get(oppositeArrowhead);
if (end.id) {
args[i] = this.paper.findViewByModel(end.id)
args[i+1] = end.selector && args[i].el.querySelector(end.selector);
}
function validateConnectionArgs(cellView, magnet) {
args[j] = cellView;
args[j+1] = cellView.el === magnet ? undefined : magnet;
return args;
}
return validateConnectionArgs;
},
startArrowheadMove: function(end) {
// Allow to delegate events from an another view to this linkView in order to trigger arrowhead
// move without need to click on the actual arrowhead dom element.
this._action = 'arrowhead-move';
this._arrowhead = end;
this._beforeArrowheadMove();
this._validateConnectionArgs = this._createValidateConnectionArgs(this._arrowhead);
},
pointerdown: function(evt, x, y) {
joint.dia.CellView.prototype.pointerdown.apply(this, arguments);
this._dx = x;
this._dy = y;
if (this.options.interactive === false) return;
var className = evt.target.getAttribute('class');
switch (className) {
case 'marker-vertex':
this._action = 'vertex-move';
this._vertexIdx = evt.target.getAttribute('idx');
break;
case 'marker-vertex-remove':
case 'marker-vertex-remove-area':
this.removeVertex(evt.target.getAttribute('idx'));
break;
case 'marker-arrowhead':
this.startArrowheadMove(evt.target.getAttribute('end'));
break;
default:
var targetParentEvent = evt.target.parentNode.getAttribute('event');
if (targetParentEvent) {
// `remove` event is built-in. Other custom events are triggered on the paper.
if (targetParentEvent === 'remove') {
this.model.remove();
} else {
this.paper.trigger(targetParentEvent, evt, this, x, y);
}
} else {
// Store the index at which the new vertex has just been placed.
// We'll be update the very same vertex position in `pointermove()`.
this._vertexIdx = this.addVertex({ x: x, y: y });
this._action = 'vertex-move';
}
}
},
pointermove: function(evt, x, y) {
joint.dia.CellView.prototype.pointermove.apply(this, arguments);
switch (this._action) {
case 'vertex-move':
var vertices = _.clone(this.model.get('vertices'));
vertices[this._vertexIdx] = { x: x, y: y };
this.model.set('vertices', vertices);
break;
case 'arrowhead-move':
// Touchmove event's target is not reflecting the element under the coordinates as mousemove does.
// It holds the element when a touchstart triggered.
var target = (evt.type === 'mousemove')
? evt.target
: document.elementFromPoint(evt.clientX, evt.clientY)
if (this._targetEvent !== target) {
// Unhighlight the previous view under pointer if there was one.
this._magnetUnderPointer && this._viewUnderPointer.unhighlight(this._magnetUnderPointer);
this._viewUnderPointer = this.paper.findView(target);
if (this._viewUnderPointer) {
// If we found a view that is under the pointer, we need to find the closest
// magnet based on the real target element of the event.
this._magnetUnderPointer = this._viewUnderPointer.findMagnet(target);
if (this._magnetUnderPointer && this.paper.options.validateConnection.apply(
this.paper, this._validateConnectionArgs(this._viewUnderPointer, this._magnetUnderPointer)
)) {
// If there was no magnet found, do not highlight anything and assume there
// is no view under pointer we're interested in reconnecting to.
// This can only happen if the overall element has the attribute `'.': { magnet: false }`.
this._magnetUnderPointer && this._viewUnderPointer.highlight(this._magnetUnderPointer);
} else {
// This type of connection is not valid. Disregard this magnet.
this._magnetUnderPointer = null;
}
} else {
// Make sure we'll delete previous magnet
this._magnetUnderPointer = null;
}
}
this._targetEvent = target;
this.model.set(this._arrowhead, { x: x, y: y });
break;
}
this._dx = x;
this._dy = y;
},
pointerup: function(evt) {
joint.dia.CellView.prototype.pointerup.apply(this, arguments);
if (this._action === 'arrowhead-move') {
if (this._magnetUnderPointer) {
this._viewUnderPointer.unhighlight(this._magnetUnderPointer);
// Find a unique `selector` of the element under pointer that is a magnet. If the
// `this._magnetUnderPointer` is the root element of the `this._viewUnderPointer` itself,
// the returned `selector` will be `undefined`. That means we can directly pass it to the
// `source`/`target` attribute of the link model below.
this.model.set(this._arrowhead, {
id: this._viewUnderPointer.model.id,
selector: this._viewUnderPointer.getSelector(this._magnetUnderPointer),
port: $(this._magnetUnderPointer).attr('port')
});
}
delete this._viewUnderPointer;
delete this._magnetUnderPointer;
delete this._staticView;
delete this._staticMagnet;
this._afterArrowheadMove();
}
delete this._action;
}
});
if (typeof exports === 'object') {
module.exports.Link = joint.dia.Link;
module.exports.LinkView = joint.dia.LinkView;
}
// JointJS library.
// (c) 2011-2013 client IO
joint.dia.Paper = Backbone.View.extend({
options: {
width: 800,
height: 600,
gridSize: 50,
perpendicularLinks: false,
elementView: joint.dia.ElementView,
linkView: joint.dia.LinkView,
// Defines what link model is added to the graph after an user clicks on an active magnet.
// Value could be the Backbone.model or a function returning the Backbone.model
// defaultLink: function(elementView, magnet) { return condition ? new customLink1() : new customLink2() }
defaultLink: new joint.dia.Link,
// Check whether to add a new link to the graph when user clicks on an a magnet.
validateMagnet: function(cellView, magnet) {
return magnet.getAttribute('magnet') !== 'passive';
},
// Check whether to allow or disallow the link connection while an arrowhead end (source/target)
// being changed.
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (end === 'target' ? cellViewT : cellViewS) instanceof joint.dia.ElementView;
}
},
events: {
'mousedown': 'pointerdown',
'dblclick': 'mousedblclick',
'touchstart': 'pointerdown',
'mousemove': 'pointermove',
'touchmove': 'pointermove'
},
initialize: function() {
_.bindAll(this, 'addCell', 'sortCells', 'resetCells', 'pointerup');
this.svg = V('svg').node;
this.viewport = V('g').node;
// Append `<defs>` element to the SVG document. This is useful for filters and gradients.
V(this.svg).append(V('defs').node);
V(this.viewport).attr({ 'class': 'viewport' });
V(this.svg).append(this.viewport);
this.$el.append(this.svg);
this.setDimensions();
this.listenTo(this.model, 'add', this.addCell);
this.listenTo(this.model, 'reset', this.resetCells);
this.listenTo(this.model, 'sort', this.sortCells);
$(document).on('mouseup touchend', this.pointerup);
},
remove: function() {
$(document).off('mouseup touchend', this.pointerup);
Backbone.View.prototype.remove.call(this);
},
setDimensions: function(width, height) {
if (width) this.options.width = width;
if (height) this.options.height = height;
V(this.svg).attr('width', this.options.width);
V(this.svg).attr('height', this.options.height);
this.trigger('resize');
},
// Expand/shrink the paper to fit the content. Snap the width/height to the grid
// defined in `gridWidth`, `gridHeight`. `padding` adds to the resulting width/height of the paper.
fitToContent: function(gridWidth, gridHeight, padding) {
gridWidth = gridWidth || 1;
gridHeight = gridHeight || 1;
padding = padding || 0;
// Calculate the paper size to accomodate all the graph's elements.
var bbox = V(this.viewport).bbox(true, this.svg);
var calcWidth = Math.ceil((bbox.width + bbox.x) / gridWidth) * gridWidth;
var calcHeight = Math.ceil((bbox.height + bbox.y) / gridHeight) * gridHeight;
calcWidth += padding;
calcHeight += padding;
// Change the dimensions only if there is a size discrepency
if (calcWidth != this.options.width || calcHeight != this.options.height) {
this.setDimensions(calcWidth || this.options.width , calcHeight || this.options.height);
}
},
createViewForModel: function(cell) {
var view;
var type = cell.get('type');
var module = type.split('.')[0];
var entity = type.split('.')[1];
// If there is a special view defined for this model, use that one instead of the default `elementView`/`linkView`.
if (joint.shapes[module] && joint.shapes[module][entity + 'View']) {
view = new joint.shapes[module][entity + 'View']({ model: cell, interactive: this.options.interactive });
} else if (cell instanceof joint.dia.Element) {
view = new this.options.elementView({ model: cell, interactive: this.options.interactive });
} else {
view = new this.options.linkView({ model: cell, interactive: this.options.interactive });
}
return view;
},
addCell: function(cell) {
var view = this.createViewForModel(cell);
V(this.viewport).append(view.el);
view.paper = this;
view.render();
// This is the only way to prevent image dragging in Firefox that works.
// Setting -moz-user-select: none, draggable="false" attribute or user-drag: none didn't help.
$(view.el).find('image').on('dragstart', function() { return false; });
},
resetCells: function(cellsCollection) {
$(this.viewport).empty();
var cells = cellsCollection.models.slice();
// Make sure links are always added AFTER elements.
// They wouldn't find their sources/targets in the DOM otherwise.
cells.sort(function(a, b) { return a instanceof joint.dia.Link ? 1 : -1; });
_.each(cells, this.addCell, this);
// Sort the cells in the DOM manually as we might have changed the order they
// were added to the DOM (see above).
this.sortCells();
},
sortCells: function() {
// Run insertion sort algorithm in order to efficiently sort DOM elements according to their
// associated model `z` attribute.
var $cells = $(this.viewport).children('[model-id]');
var cells = this.model.get('cells');
// Using the jquery.sortElements plugin by Padolsey.
// See http://james.padolsey.com/javascript/sorting-elements-with-jquery/.
$cells.sortElements(function(a, b) {
var cellA = cells.get($(a).attr('model-id'));
var cellB = cells.get($(b).attr('model-id'));
return (cellA.get('z') || 0) > (cellB.get('z') || 0) ? 1 : -1;
});
},
scale: function(sx, sy, ox, oy) {
if (!ox) {
ox = 0;
oy = 0;
}
// Remove previous transform so that the new scale is not affected by previous scales, especially
// the old translate() does not affect the new translate if an origin is specified.
V(this.viewport).attr('transform', '');
// TODO: V.scale() doesn't support setting scale origin. #Fix
if (ox || oy) {
V(this.viewport).translate(-ox * (sx - 1), -oy * (sy - 1));
}
V(this.viewport).scale(sx, sy);
this.trigger('scale', ox, oy);
return this;
},
rotate: function(deg, ox, oy) {
// If the origin is not set explicitely, rotate around the center. Note that
// we must use the plain bounding box (`this.el.getBBox()` instead of the one that gives us
// the real bounding box (`bbox()`) including transformations).
if (_.isUndefined(ox)) {
var bbox = this.viewport.getBBox();
ox = bbox.width/2;
oy = bbox.height/2;
}
V(this.viewport).rotate(deg, ox, oy);
},
zoom: function(level) {
level = level || 1;
V(this.svg).attr('width', this.options.width * level);
V(this.svg).attr('height', this.options.height * level);
},
// Find the first view climbing up the DOM tree starting at element `el`. Note that `el` can also
// be a selector or a jQuery object.
findView: function(el) {
var $el = this.$(el);
if ($el.length === 0 || $el[0] === this.el) {
return undefined;
}
if ($el.data('view')) {
return $el.data('view');
}
return this.findView($el.parent());
},
// Find a view for a model `cell`. `cell` can also be a string representing a model `id`.
findViewByModel: function(cell) {
var id = _.isString(cell) ? cell : cell.id;
var $view = this.$('[model-id="' + id + '"]');
if ($view.length) {
return $view.data('view');
}
return undefined;
},
// Find all views at given point
findViewsFromPoint: function(p) {
p = g.point(p);
var views = _.map(this.model.getElements(), this.findViewByModel);
return _.filter(views, function(view) {
return g.rect(view.getBBox()).containsPoint(p);
});
},
// Find all views in given area
findViewsInArea: function(r) {
r = g.rect(r);
var views = _.map(this.model.getElements(), this.findViewByModel);
return _.filter(views, function(view) {
return r.intersect(g.rect(view.getBBox()));
});
},
getModelById: function(id) {
return this.model.getCell(id);
},
snapToGrid: function(p) {
// Convert global coordinates to the local ones of the `viewport`. Otherwise,
// improper transformation would be applied when the viewport gets transformed (scaled/rotated).
var localPoint = V(this.viewport).toLocalPoint(p.x, p.y);
return {
x: g.snapToGrid(localPoint.x, this.options.gridSize),
y: g.snapToGrid(localPoint.y, this.options.gridSize)
};
},
getDefaultLink: function(cellView, magnet) {
return _.isFunction(this.options.defaultLink)
// default link is a function producing link model
? this.options.defultLink.call(this, cellView, magnet)
// default link is the Backbone model
: this.options.defaultLink.clone();
},
// Interaction.
// ------------
mousedblclick: function(evt) {
evt.preventDefault();
evt = joint.util.normalizeEvent(evt);
var view = this.findView(evt.target);
var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
if (view) {
view.pointerdblclick(evt, localPoint.x, localPoint.y);
} else {
this.trigger('blank:pointerdblclick', evt, localPoint.x, localPoint.y);
}
},
pointerdown: function(evt) {
evt.preventDefault();
evt = joint.util.normalizeEvent(evt);
var view = this.findView(evt.target);
var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
if (view) {
this.sourceView = view;
view.pointerdown(evt, localPoint.x, localPoint.y);
} else {
this.trigger('blank:pointerdown', evt, localPoint.x, localPoint.y);
}
},
pointermove: function(evt) {
evt.preventDefault();
evt = joint.util.normalizeEvent(evt);
if (this.sourceView) {
var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
this.sourceView.pointermove(evt, localPoint.x, localPoint.y);
}
},
pointerup: function(evt) {
evt = joint.util.normalizeEvent(evt);
var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
if (this.sourceView) {
this.sourceView.pointerup(evt, localPoint.x, localPoint.y);
//"delete sourceView" occasionally throws an error in chrome (illegal access exception)
this.sourceView = null;
} else {
this.trigger('blank:pointerup', evt, localPoint.x, localPoint.y);
}
}
});
// JointJS library.
// (c) 2011-2013 client IO
if (typeof exports === 'object') {
var joint = {
util: require('../src/core').util,
shapes: {},
dia: {
Element: require('../src/joint.dia.element').Element
}
};
var _ = require('lodash');
}
joint.shapes.basic = {};
joint.shapes.basic.Generic = joint.dia.Element.extend({
defaults: joint.util.deepSupplement({
type: 'basic.Generic',
attrs: {
'.': { fill: '#FFFFFF', stroke: 'none' }
}
}, joint.dia.Element.prototype.defaults)
});
joint.shapes.basic.Rect = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Rect',
attrs: {
'rect': { fill: '#FFFFFF', stroke: 'black', width: 100, height: 60 },
'text': { 'font-size': 14, text: '', 'ref-x': .5, 'ref-y': .5, ref: 'rect', 'y-alignment': 'middle', 'x-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Text = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><text/></g></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Text',
attrs: {
'text': { 'font-size': 18, fill: 'black' }
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Circle = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><circle/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Circle',
size: { width: 60, height: 60 },
attrs: {
'circle': { fill: '#FFFFFF', stroke: 'black', r: 30, transform: 'translate(30, 30)' },
'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-y': .5, ref: 'circle', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Image = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><image/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Image',
attrs: {
'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, ref: 'image', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Path = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><path/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Path',
size: { width: 60, height: 60 },
attrs: {
'path': { fill: '#FFFFFF', stroke: 'black' },
'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, ref: 'path', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' }
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
// PortsModelInterface is a common interface for shapes that have ports. This interface makes it easy
// to create new shapes with ports functionality. It is assumed that the new shapes have
// `inPorts` and `outPorts` array properties. Only these properties should be used to set ports.
// In other words, using this interface, it is no longer recommended to set ports directly through the
// `attrs` object.
// Usage:
// joint.shapes.custom.MyElementWithPorts = joint.shapes.basic.Path.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, {
// getPortAttrs: function(portName, index, total, selector, type) {
// var attrs = {};
// var portClass = 'port' + index;
// var portSelector = selector + '>.' + portClass;
// var portTextSelector = portSelector + '>text';
// var portCircleSelector = portSelector + '>circle';
//
// attrs[portTextSelector] = { text: portName };
// attrs[portCircleSelector] = { port: { id: portName || _.uniqueId(type) , type: type } };
// attrs[portSelector] = { ref: 'rect', 'ref-y': (index + 0.5) * (1 / total) };
//
// if (selector === '.outPorts') { attrs[portSelector]['ref-dx'] = 0; }
//
// return attrs;
// }
//}));
joint.shapes.basic.PortsModelInterface = {
initialize: function() {
this.updatePortsAttrs();
this.on('change:inPorts change:outPorts', this.updatePortsAttrs, this);
// Call the `initialize()` of the parent.
this.constructor.__super__.constructor.__super__.initialize.apply(this, arguments);
},
updatePortsAttrs: function(eventName) {
// Delete previously set attributes for ports.
var currAttrs = this.get('attrs');
_.each(this._portSelectors, function(selector) {
if (currAttrs[selector]) delete currAttrs[selector];
});
// This holds keys to the `attrs` object for all the port specific attribute that
// we set in this method. This is necessary in order to remove previously set
// attributes for previous ports.
this._portSelectors = [];
var attrs = {};
_.each(this.get('inPorts'), function(portName, index, ports) {
var portAttributes = this.getPortAttrs(portName, index, ports.length, '.inPorts', 'in');
this._portSelectors = this._portSelectors.concat(_.keys(portAttributes));
_.extend(attrs, portAttributes);
}, this);
_.each(this.get('outPorts'), function(portName, index, ports) {
var portAttributes = this.getPortAttrs(portName, index, ports.length, '.outPorts', 'out');
this._portSelectors = this._portSelectors.concat(_.keys(portAttributes));
_.extend(attrs, portAttributes);
}, this);
// Silently set `attrs` on the cell so that noone knows the attrs have changed. This makes sure
// that, for example, command manager does not register `change:attrs` command but only
// the important `change:inPorts`/`change:outPorts` command.
this.attr(attrs, { silent: true });
// Manually call the `processPorts()` method that is normally called on `change:attrs` (that we just made silent).
this.processPorts();
// Let the outside world (mainly the `ModelView`) know that we're done configuring the `attrs` object.
this.trigger('process:ports');
},
getPortSelector: function(name) {
var selector = '.inPorts';
var index = this.get('inPorts').indexOf(name);
if (index < 0) {
selector = '.outPorts';
index = this.get('outPorts').indexOf(name);
if (index < 0) throw new Error("getPortSelector(): Port doesn't exist.");
}
return selector + '>g:nth-child(' + (index + 1) + ')>circle';
}
};
joint.shapes.basic.PortsViewInterface = {
initialize: function() {
// `Model` emits the `process:ports` whenever it's done configuring the `attrs` object for ports.
this.listenTo(this.model, 'process:ports', this.update);
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
},
update: function() {
// First render ports so that `attrs` can be applied to those newly created DOM elements
// in `ElementView.prototype.update()`.
this.renderPorts();
joint.dia.ElementView.prototype.update.apply(this, arguments);
},
renderPorts: function() {
var $inPorts = this.$('.inPorts').empty();
var $outPorts = this.$('.outPorts').empty();
var portTemplate = _.template(this.model.portMarkup);
_.each(_.filter(this.model.ports, function(p) { return p.type === 'in' }), function(port, index) {
$inPorts.append(V(portTemplate({ id: index, port: port })).node);
});
_.each(_.filter(this.model.ports, function(p) { return p.type === 'out' }), function(port, index) {
$outPorts.append(V(portTemplate({ id: index, port: port })).node);
});
}
};
joint.shapes.basic.TextBlock = joint.shapes.basic.Rect.extend({
markup: ['<g class="rotatable"><g class="scalable"><rect/></g><switch>',
// if foreignObject supported
'<foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" class="fobj">',
'<body xmlns="http://www.w3.org/1999/xhtml"><div/></body>',
'</foreignObject>',
// else foreignObject is not supported (fallback for IE)
'<svg overflow="hidden"><text/></svg>',
'</switch></g>'].join(''),
defaults: joint.util.deepSupplement({
type: 'basic.TextBlock',
// see joint.css for the element styles
content: ''
}, joint.shapes.basic.Rect.prototype.defaults),
initialize: function() {
if (typeof SVGForeignObjectElement !== 'undefined') {
// foreignObject supported
this.setForeignObjectSize(this, this.get('size'));
this.setDivContent(this, this.get('content'));
this.listenTo(this, 'change:size', this.setForeignObjectSize);
this.listenTo(this, 'change:content', this.setDivContent);
} else {
// no foreignObject
this.setSvgSize(this, this.get('size'));
this.setTextContent(this, this.get('content'));
this.listenTo(this, 'change:size', this.setSvgSize);
this.listenTo(this, 'change:content', this.setTextContent);
}
joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments);
},
setForeignObjectSize: function(cell, size) {
// Selector `foreignObject' doesn't work accross all browsers, we'r using class selector instead.
// We have to clone size as we don't want attributes.div.style to be same object as attributes.size.
cell.attr({
'.fobj': _.clone(size),
div: { style: _.clone(size) }
});
},
setSvgSize: function(cell, size) {
// Trim a text overflowing the element.
cell.attr({ svg: _.clone(size) });
},
setDivContent: function(cell, content) {
// Append the content to div as html.
cell.attr({ div : {
html: content
}});
},
setTextContent: function(cell, content) {
// This could be overriden in order to break the text lines to fit to a content of the element.
cell.attr({ text: {
text: content
}});
}
});
if (typeof exports === 'object') {
module.exports = joint.shapes.basic;
} |
src/components/Profile/common/components/Timeline.js | TalentedEurope/te-app | import React from 'react';
import { Text, StyleSheet, View } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import COMMON_STYLES from '../../../../styles/common';
export const Timeline = (props) => {
const listItems = props.items.map(item => (
<View style={styles.item} key={item.id}>
<Icon name="circle" size={10} style={styles.dot} />
<Text style={styles.dateLine}>{item.dateLine}</Text>
<Text>{item.title}</Text>
</View>
));
return <View style={styles.timelineWrapper}>{listItems}</View>;
};
const styles = StyleSheet.create({
dateLine: {
color: COMMON_STYLES.TEXT_GRAY,
fontSize: 12,
marginBottom: 5,
fontStyle: 'italic',
},
dot: {
color: COMMON_STYLES.BLUE,
position: 'absolute',
left: -4,
top: 5,
},
item: {
paddingLeft: 10,
borderLeftColor: COMMON_STYLES.GRAY,
borderLeftWidth: StyleSheet.hairlineWidth,
paddingBottom: 15,
},
});
|
core/src/plugins/gui.ajax/res/js/ui/Workspaces/detailpanes/RootNode.js | pydio/pydio-core | /*
* Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
import React from 'react'
import InfoPanelCard from './InfoPanelCard'
export default React.createClass({
getInitialState() {
return {
repoKey: null
}
},
componentDidMount() {
this.loadData(this.props);
},
componentWillReceiveProps(nextProps) {
if (nextProps.pydio.user && nextProps.pydio.user.activeRepository != this.state.repoKey) {
this.loadData(nextProps);
}
},
loadData(props) {
if(!props.pydio.user) {
return;
}
let cacheService = MetaCacheService.getInstance();
cacheService.registerMetaStream('workspace.info', 'MANUAL_TRIGGER');
let oThis = this;
const render = function(data){
oThis.setState({...data['core.users']});
};
const repoKey = pydio.user.getActiveRepository();
this.setState({repoKey: repoKey})
if(cacheService.hasKey('workspace.info', repoKey)){
render(cacheService.getByKey('workspace.info', repoKey));
}else{
FuncUtils.bufferCallback("ajxp_load_repo_info_timer", 700,function(){
if(!oThis.isMounted()) return;
PydioApi.getClient().request({get_action:'load_repository_info'}, function(transport) {
if(transport.responseJSON){
var data = transport.responseJSON;
if(!data['core.users']['groups']){
data['core.users']['groups'] = 0;
}
}
cacheService.registerMetaStream('workspace.info', 'MANUAL_TRIGGER');
cacheService.setKey('workspace.info', repoKey, data);
render(data);
}, null, {discrete:true});
});
}
},
render() {
const messages = this.props.pydio.MessageHash;
let internal = messages[528];
let external = messages[530];
let shared = messages[527];
let content, panelData;
if(this.state && this.state.users){
panelData = [
{key: 'internal', label:internal, value:this.state.users},
{key: 'external', label:external, value:this.state.groups}
];
}
return (
<InfoPanelCard title={messages[249]} style={this.props.style} standardData={panelData} icon="account-multiple-outline" iconColor="00838f">{content}</InfoPanelCard>
);
}
});
|
docs/src/sections/GridPaginationSection.js | yyssc/ssc-grid | import React from 'react';
import Anchor from '../Anchor';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function GridSection() {
return (
<div className="bs-docs-section">
<h3><Anchor id="grid-pagination">显示分页</Anchor></h3>
<p>使用<code>paging</code>参数显示分页</p>
<ReactPlayground codeText={Samples.GridPagination} />
</div>
);
}
|
webpack/scenes/Subscriptions/components/SubscriptionsTable/SubscriptionTypeFormatter.js | snagoor/katello | import React from 'react';
import { translate as __ } from 'foremanReact/common/I18n';
import { urlBuilder } from 'foremanReact/common/urlHelpers';
export const subscriptionTypeFormatter = (value, { rowData }) => {
let cellContent;
if (rowData.virt_only === false) {
cellContent = __('Physical');
} else if (rowData.hypervisor) {
const hypervisorLink = urlBuilder('content_hosts', '', rowData.hypervisor.id);
cellContent = (
<span>
{__('Guests of')}
{' '}
<a href={hypervisorLink}>{rowData.hypervisor.name}</a>
</span>
);
} else if (rowData.unmapped_guest) {
cellContent = __('Temporary');
} else {
cellContent = __('Virtual');
}
return (
<td>
{cellContent}
</td>
);
};
export default subscriptionTypeFormatter;
|
src/index.js | crp2002/ID3-React | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import promise from 'redux-promise';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import App from './components/App';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(promise, thunk, logger)(createStore);
export let store = createStoreWithMiddleware(reducers)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.querySelector('.main-container'));
|
app/components/PointModal/index.js | GuiaLa/guiala-web-app | /**
*
* PointModal
*
*/
import React, { Component } from 'react';
import {
Step,
Stepper,
StepLabel,
} from 'material-ui/Stepper';
import { Tabs, Tab } from 'material-ui/Tabs';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Checkbox from 'material-ui/Checkbox';
import styles from './styles.css';
const regions = [
{
name: 'Região 1'
},
{
name: 'Região 2'
}
]
const types = [
{
name: 'Atrativo',
value: 'fun'
}, {
name: 'Hospedagem',
value: 'stay'
}, {
name: 'Alimentação',
value: 'eat'
},
]
const catsFunDificulty = [
{
name: 'Fácil',
value: 1
}, {
name: 'Médio',
value: 2
}, {
name: 'Difícil',
value: 3
},
]
const catsFunPrice = [
{
name: 'Grátis',
value: 0
}, {
name: 'Valor Baixo',
value: 1
}, {
name: 'Valor Médio',
value: 2
}, {
name: 'Valor Alto',
value: 3
},
]
const catsFunAccess = [
{
name: 'Pé',
value: 'foot'
}, {
name: 'Bicicleta',
value: 'bike'
}, {
name: 'Carros',
value: 'cars'
}, {
name: '4x4',
value: '4x4'
},
]
class PointModal extends Component {
constructor(props) {
super(props);
this.state = {
finished: false,
stepIndex: 0,
name: '',
slug: '',
description: '',
region: '',
type: 'fun',
categories: [],
coords: [],
owner: '',
managers: [],
theme: 'default'
}
}
handleSubmit = () => {
const { name, slug, description, region, type, categories, coords, owner, managers, theme } = this.state;
this.props.addPoint({
name, slug, description, region, type, categories, coords, owner, managers, theme
})
}
handleFormName = (e) => {
this.setState({
name: e.target.value
})
}
handleFormSlug = (e) => {
this.setState({
slug: e.target.value
})
}
handleFormDescription = (e) => {
this.setState({
description: e.target.value
})
}
handleFormRegion = (e, index, value) => {
this.setState({
region: value
})
}
handleFormType = (e, index, value) => {
console.log(value);
this.setState({
type: value
})
}
handleFormCoords = (e, index, value) => {
console.log(value);
this.setState({
coords: value
})
}
handleCatsDificulty = (e, index, value) => {
console.log(value);
const newValue = this.state.categories.concat(value)
this.setState({
categories: newValue
})
}
handleCatsPrice = (e, index, value) => {
console.log(value);
const newValue = this.state.categories.concat(value)
this.setState({
categories: newValue
})
}
handleCatsAccess = (e, index, value) => {
console.log(value);
const newValue = this.state.categories.concat(value)
this.setState({
categories: newValue
})
}
handleNext = () => {
const {stepIndex} = this.state;
this.setState({
stepIndex: stepIndex + 1,
finished: stepIndex >= 2,
});
};
handlePrev = () => {
const {stepIndex} = this.state;
if (stepIndex > 0) {
this.setState({stepIndex: stepIndex - 1});
}
};
getStepContent(stepIndex) {
const { name, slug, description, region, categories, type } = this.state;
switch (stepIndex) {
case 0:
return (
<div>
<TextField
hintText="Nome do ponto"
value={name}
onChange={this.handleFormName.bind(this)}/><br/>
<TextField
hintText="Slug"
value={slug}
onChange={this.handleFormSlug.bind(this)}/><br/>
<SelectField value={type} onChange={this.handleFormType}>
{types.map((t, key) => {
return <MenuItem key={key} value={t.value} primaryText={t.name} />
})}
</SelectField>
</div>
);
case 1:
return (
<div>
<SelectField value={regions[0].name} onChange={this.handleFormRegion}>
{regions.map((regionOption, key) => {
return <MenuItem key={key} value={regionOption.name} label={regionOption.name} primaryText={regionOption.name} />
})}
</SelectField>
<TextField
floatingLabelText="Descrição"
hintText="Uma breve descrição a respeito do ponto"
multiLine={true}
rows={6}
fullWidth={true}
onChange={this.handleFormDescription.bind(this)}
value={description}></TextField>
</div>
);
case 2:
return (
<div>
<SelectField value={type} onChange={this.handleCatsDificulty}>
{catsFunDificulty.map((t, key) => {
return <MenuItem key={key} value={t.value} primaryText={t.name} />
})}
</SelectField>
<SelectField value={type} onChange={this.handleCatsPrice}>
{catsFunPrice.map((t, key) => {
return <MenuItem key={key} value={t.value} primaryText={t.name} />
})}
</SelectField>
<SelectField value={type} onChange={this.handleCatsAccess}>
{catsFunAccess.map((t, key) => {
return <MenuItem key={key} value={t.value} primaryText={t.name} />
})}
</SelectField>
</div>
);
default:
return 'You\'re a long way from home sonny jim!';
}
}
render() {
const { pointModal, closePointModal, addPoint, current } = this.props;
const { stepIndex, finished } = this.state;
const actions = [
<FlatButton
label="Cancel"
secondary={true}
onTouchTap={closePointModal}
/>,
<FlatButton
label="Submit"
primary={true}
onTouchTap={this.handleSubmit}
/>,
];
return (
<div className={ styles.wrapper }>
<Dialog
title={`Novo Ponto em ${current}`}
actions={actions}
contentStyle={{width: '100%'}}
modal={true}
open={pointModal}
autoScrollBodyContent={true}
bodyStyle={{padding: '0 0 100px'}}>
<Tabs>
<Tab label="Novo">
<Stepper>
<Step>
<StepLabel></StepLabel>
</Step>
<Step>
<StepLabel></StepLabel>
</Step>
<Step>
<StepLabel></StepLabel>
</Step>
</Stepper>
<div style={{width: '90%', margin: '0 auto'}}>
{finished ? (
<p><a href="#" onClick={(event) => { event.preventDefault(); this.setState({stepIndex: 0, finished: false});}}>
Click aqui
</a> para voltar ao início.</p>
)
: (
<div>
{this.getStepContent(stepIndex)}
<div style={{marginTop: 12}}>
<FlatButton
label="Voltar"
disabled={stepIndex === 0}
onTouchTap={this.handlePrev}
style={{marginRight: 12}}
/>
<RaisedButton
label={stepIndex === 2 ? 'Enviar' : 'Próximo'}
primary={true}
onTouchTap={this.handleNext}
/>
</div>
</div>
)}
</div>
</Tab>
<Tab label="Editar" >
<h1>Editar em breve</h1>
</Tab>
</Tabs>
</Dialog>
</div>
);
}
}
export default PointModal;
|
components/about.js | nayed/universal-react | import React from 'react'
export default class AboutComponent extends React.Component {
render() {
return (
<div>
<p>Hi mom!</p>
</div>
)
}
} |
examples/huge-apps/routes/Course/routes/Assignments/routes/Assignment/components/Assignment.js | schnerd/react-router | /*globals COURSES:true */
import React from 'react'
class Assignment extends React.Component {
render() {
let { courseId, assignmentId } = this.props.params
let { title, body } = COURSES[courseId].assignments[assignmentId]
return (
<div>
<h4>{title}</h4>
<p>{body}</p>
</div>
)
}
}
export default Assignment
|
platform/ui/src/viewer/Toolbar.js | OHIF/Viewers | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import SimpleToolbarButton from './SimpleToolbarButton';
import PlayClipButton from './PlayClipButton';
import { LayoutButton } from './../components/layoutButton';
// TODO: This should not be built in the `@ohif/ui` component
function getDefaultButtonData() {
var buttonData = [
{
id: 'wwwc',
title: 'WW/WC',
className: 'imageViewerTool',
icon: 'sun',
},
{
id: 'wwwcRegion',
title: 'Window by Region',
className: 'imageViewerTool',
icon: 'stop',
},
{
id: 'magnify',
title: 'Magnify',
className: 'imageViewerTool',
icon: 'circle',
},
{
id: 'annotate',
title: 'Annotation',
className: 'imageViewerTool',
icon: 'arrows-alt-h',
},
{
id: 'invert',
title: 'Invert',
className: 'imageViewerCommand',
icon: 'adjust',
},
{
id: 'zoom',
title: 'Zoom',
className: 'imageViewerTool',
icon: 'search-plus',
},
{
id: 'pan',
title: 'Pan',
className: 'imageViewerTool',
icon: 'arrows',
},
{
id: 'stackScroll',
title: 'Stack Scroll',
className: 'imageViewerTool',
icon: 'bars',
},
{
id: 'length',
title: 'Length Measurement',
className: 'imageViewerTool',
icon: 'arrows-alt-v',
},
{
id: 'angle',
title: 'Angle Measurement',
className: 'imageViewerTool',
icon: 'fa fa-angle-left',
},
{
id: 'dragProbe',
title: 'Pixel Probe',
className: 'imageViewerTool',
icon: 'fa fa-dot-circle-o',
},
{
id: 'ellipticalRoi',
title: 'Elliptical ROI',
className: 'imageViewerTool',
icon: 'circle-o',
},
{
id: 'rectangleRoi',
title: 'Rectangle ROI',
className: 'imageViewerTool',
icon: 'square-o',
},
{
id: 'resetViewport',
title: 'Reset Viewport',
className: 'imageViewerCommand',
icon: 'reset',
},
{
id: 'clearTools',
title: 'Clear tools',
className: 'imageViewerCommand',
icon: 'trash',
},
];
return buttonData;
}
export default class Toolbar extends Component {
static propTypes = {
buttons: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
icon: PropTypes.oneOfType([
PropTypes.string,
PropTypes.shape({
name: PropTypes.string.isRequired,
}),
]),
})
).isRequired,
includeLayoutButton: PropTypes.bool.isRequired,
includePlayClipButton: PropTypes.bool.isRequired,
};
static defaultProps = {
buttons: getDefaultButtonData(),
includeLayoutButton: true,
includePlayClipButton: true,
};
render() {
var maybePlayClipButton;
if (this.props.includePlayClipButton) {
maybePlayClipButton = <PlayClipButton />;
}
var maybeLayoutButton;
if (this.props.includeLayoutButton) {
maybeLayoutButton = <LayoutButton />;
}
return (
<div id="toolbar">
<div className="btn-group">
{this.props.buttons.map((button, i) => {
return <SimpleToolbarButton {...button} key={i} />;
})}
{maybePlayClipButton}
{maybeLayoutButton}
</div>
</div>
);
}
}
|
src/js/components/Articles/Index.js | appdev-academy/appdev.academy-react | import React from 'react'
import { Link } from 'react-router'
import { inject, observer } from 'mobx-react'
import TableBody from './TableBody'
import ConfirmationDialog from '../ConfirmationDialog'
@inject('articlesStore')
@observer
export default class Index extends React.Component {
constructor(props) {
super(props)
this.state = {
deleteConfirmationDialogShow: false,
deleteConfirmationDialogEntityID: null,
deleteConfirmationDialogEntityTitle: null
}
}
componentDidMount() {
this.props.articlesStore.fetchIndex()
}
moveArticle(startIndex, dropIndex) {
if (startIndex == dropIndex) {
return
}
let articleIDs = this.props.articlesStore.articles.map((article) => article.id)
let draggedArticleID = articleIDs[startIndex]
articleIDs.splice(startIndex, 1)
articleIDs.splice(dropIndex, 0, draggedArticleID)
// Sort Articles on server (assign position property to each Article according to order of IDs)
this.props.articlesStore.sort(articleIDs)
}
showDeleteConfirmationDialog(entity) {
this.setState({
deleteConfirmationDialogShow: true,
deleteConfirmationDialogEntityID: entity.id,
deleteConfirmationDialogEntityTitle: entity.title
})
}
hideDeleteConfirmationDialog() {
this.setState({
deleteConfirmationDialogShow: false,
deleteConfirmationDialogEntityID: null,
deleteConfirmationDialogEntityTitle: null
})
}
deleteButtonClick() {
this.props.articlesStore.delete(this.state.deleteConfirmationDialogEntityID);
this.setState({
deleteConfirmationDialogShow: false,
deleteConfirmationDialogEntityID: null,
deleteConfirmationDialogEntityTitle: null
})
}
render() {
return (
<div className='articles'>
<h2 className='center'>Articles</h2>
<Link className='button blue' to='/articles/new'>+ New Article</Link>
<br />
<br />
<table className='admin'>
<thead>
<tr>
<td>ID</td>
<td>Title</td>
<td>Slug</td>
<td>Position</td>
<td>Actions</td>
<td>Publish</td>
</tr>
</thead>
<TableBody
articles={ this.props.articlesStore.articles }
publishButtonClick={ (articleID) => { this.props.articlesStore.publish(articleID) }}
hideButtonClick={ (articleID) => { this.props.articlesStore.hide(articleID) }}
deleteButtonClick={ (article) => { this.showDeleteConfirmationDialog(article) }}
moveArticle={ this.moveArticle.bind(this) }
/>
</table>
<ConfirmationDialog
actionButtonClick={ () => { this.deleteButtonClick() }}
actionName='delete'
cancelButtonClick= { () => { this.hideDeleteConfirmationDialog() }}
destructive={ true }
entityName='article'
entityTitle={ this.state.deleteConfirmationDialogEntityTitle }
show={ this.state.deleteConfirmationDialogShow }
/>
</div>
)
}
}
|
node_modules/react-icons/fa/arrow-up.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const FaArrowUp = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m37.5 21.7q0 1.1-0.9 2l-1.6 1.7q-0.9 0.8-2.1 0.8-1.2 0-2-0.8l-6.5-6.6v15.7q0 1.2-0.9 1.9t-2 0.7h-2.9q-1.1 0-2-0.7t-0.8-1.9v-15.7l-6.6 6.6q-0.8 0.8-2 0.8t-2-0.8l-1.7-1.7q-0.8-0.9-0.8-2 0-1.2 0.8-2.1l14.6-14.5q0.7-0.8 2-0.8 1.2 0 2 0.8l14.5 14.5q0.9 0.9 0.9 2.1z"/></g>
</Icon>
)
export default FaArrowUp
|
packages/mineral-ui-icons/src/IconPeople.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconPeople(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/>
</g>
</Icon>
);
}
IconPeople.displayName = 'IconPeople';
IconPeople.category = 'social';
|
server/server.js | kweestian/kwy | import Express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import path from 'path';
import logger from 'morgan';
// Webpack Requirements
import webpack from 'webpack';
import config from '../webpack.config.dev';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import { middleWare, middleWareConnections } from './middleware/sse';
// Initialize the Express App
const app = new Express();
app.use(cookieParser());
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: { httpOnly: true }
}));
app.use(middleWare);
if (process.env.NODE_ENV !== 'production') {
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
app.use(logger('dev'));
}
// React And Redux Setup
import { configureStore } from '../shared/redux/store/configureStore';
import { Provider } from 'react-redux';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
// Import required modules
import getRoutes from '../shared/routes';
import { fetchComponentData } from './util/fetchData';
// import posts from './routes/post.routes';
import api from './routes/api.routes';
import auth from './routes/auth.routes';
import dummyData from './dummyData';
import serverConfig from './config';
import passport from './passport';
// MongoDB Connection
// https://github.com/Automattic/mongoose/issues/4291
mongoose.Promise = global.Promise;
mongoose.connect(serverConfig.mongoURL, (error) => {
if (error) {
console.log(serverConfig.mongoURL);
console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console
throw error;
}
// feed some dummy data in DB.
dummyData();
});
// Apply body Parser and server public assets and routes
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use(Express.static(path.resolve(__dirname, '../static')));
app.use(passport.initialize());
app.use((req, res, next) => {
// console.log('token');
// console.log(req.session);
next();
});
app.use('/api', api);
app.use('/auth', auth);
// Set up stream
app.get('/stream', (req, res) => {
res.sseSetup();
middleWareConnections.push(res);
});
// Render Initial HTML
const renderFullPage = (html, initialState) => {
const cssPath = 'css/app.css';
const cssVendorPath = 'vendor/css';
const jsVendorPath = 'vendor/js';
return `
<!doctype html>
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:og="http://ogp.me/ns#"
xmlns:fb="https://www.facebook.com/2008/fbml"
>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:type" content="website">
<meta property="og:image" content="http://s32.postimg.org/lctx7fjz9/luke_poster_kwy.png">
<meta property="og:description" content="A Cancer Foundation">
<title>Kids Without Yachts</title>
<link rel="stylesheet" href=${cssPath} />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
<link rel="stylesheet" href=${cssVendorPath}/animate.css />
<link rel="stylesheet" href=${cssVendorPath}/bootstrap.min.css />
<link rel="stylesheet" href=${cssVendorPath}/team.css />
<link rel="stylesheet" href=${cssVendorPath}/full-width-pics.css />
<link rel="stylesheet" href=${cssVendorPath}/full-screen-image.css />
<link rel="stylesheet" href="css/bootstrap_overrides.css" />
<link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato:400,300,700" rel="stylesheet" type="text/css"/>
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon">
<link rel="icon" href="/img/favicon.ico" type="image/x-icon">
<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
document,'script','https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '175684682930900'); // Insert your pixel ID here.
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=175684682930900&ev=PageView&noscript=1"/>
</noscript>
<!-- DO NOT MODIFY -->
<!-- End Facebook Pixel Code -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-92238984-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top" class="animated fadeIn">
<div id="root">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
</script>
<script src="/dist/bundle.js"></script>
<script src="${jsVendorPath}/jquery.min.js"></script>
<script src="${jsVendorPath}/jquery.easing.min.js"></script>
<script src="${jsVendorPath}/bootstrap.min.js"></script>
<script src="${jsVendorPath}/grayscale.js"></script>
</body>
</html>
`;
};
const renderError = err => {
const softTab = '    ';
const errTrace = process.env.NODE_ENV !== 'production' ?
`:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : '';
return renderFullPage(`Server Error${errTrace}`, {});
};
// Server Side Rendering based on routes matched by React-router.
app.use((req, res, next) => {
const initialState = {
post: { posts: [], post: {} },
auth: { isAuthenticated: false, isFetching: false }
};
const store = configureStore(initialState);
match({ routes: getRoutes(store, req), location: req.url }, (err, redirectLocation, renderProps) => {
if (err) {
return res.status(500).end(renderError(err));
}
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
if (!renderProps) {
return next();
}
return fetchComponentData(store, renderProps.components, renderProps.params)
.then(() => {
const initialView = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
);
const finalState = store.getState();
res.status(200).end(renderFullPage(initialView, finalState));
});
});
});
// start app
app.listen(serverConfig.port, (error) => {
if (!error) {
console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line
}
});
export default app;
|
src/interface/Portal.js | sMteX/WoWAnalyzer | import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import PortalTarget from './PortalTarget';
class Portal extends React.PureComponent {
static propTypes = {
children: PropTypes.node.isRequired,
};
state = {
elem: null,
};
componentDidMount() {
this.setState({
elem: PortalTarget.newElement(),
});
}
componentWillUnmount() {
PortalTarget.remove(this.state.elem);
}
render() {
if (!this.state.elem) {
return null;
}
return ReactDOM.createPortal(
this.props.children,
this.state.elem
);
}
}
export default Portal;
|
project/react-ant-multi-pages/src/base/BaseFormContainer.js | FFF-team/generator-earth | import React from 'react'
import { Form } from 'antd'
import BaseContainer from './BaseContainer'
export default class extends BaseContainer {
/**
* 提交表单
* @override
*/
submitForm = (e) => {
e && e.preventDefault()
// 重置table
this.props.resetTable && this.props.resetTable()
// 提交表单最好新一个事务,不受其他事务影响
setTimeout( () => {
let _formData = { ...this.props.form.getFieldsValue() }
// _formData里的一些值需要适配
_formData = this.adaptFormData(_formData)
// action
this.props.updateTable && this.props.updateTable(_formData)
}, 0 )
}
/**
* this.props.formData里的一些值需要适配
* @override
*/
adaptFormData(formData) {
return formData
}
/**
* 包裹表单项
*/
wrapItems(items) {
return (
<div className="ui-background">
<Form layout="inline" onSubmit={this.submitForm}>
{items}
</Form>
</div>
)
}
}
|
client/libraries/swamp/chat_example/chat_example/static/js/vendor/jquery-1.8.0.min.js | Valchris/tdoa | /*! jQuery v@1.8.0 jquery.com | jquery.org/license */
(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bX(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bV.length;while(e--){b=bV[e]+c;if(b in a)return b}return d}function bY(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function bZ(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bY(c)&&(e[f]=p._data(c,"olddisplay",cb(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b$(a,b,c){var d=bO.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function b_(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bU[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bU[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bU[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bU[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bU[e]+"Width"))||0));return f}function ca(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bP.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+b_(a,b,c||(f?"border":"content"),e)+"px"}function cb(a){if(bR[a])return bR[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cz(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cu;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cz(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cz(a,c,d,e,"*",g)),h}function cA(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cB(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cC(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cK(){try{return new a.XMLHttpRequest}catch(b){}}function cL(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cT(){return setTimeout(function(){cM=b},0),cM=p.now()}function cU(a,b){p.each(b,function(b,c){var d=(cS[b]||[]).concat(cS["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cV(a,b,c){var d,e=0,f=0,g=cR.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cM||cT(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cM||cT(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cW(k,j.opts.specialEasing);for(;e<g;e++){d=cR[e].call(j,a,k,j.opts);if(d)return d}return cU(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cW(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cX(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bY(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cb(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cO.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cY(a,b,c,d,e){return new cY.prototype.init(a,b,c,d,e)}function cZ(a,b){var c,d={height:a},e=0;for(;e<4;e+=2-b)c=bU[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function c_(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=r.test(" ")?/^[\s\xA0]+|[\s\xA0]+$/g:/^\s+|\s+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":a.toString().replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||f.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete"||e.readyState!=="loading"&&e.addEventListener)setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){p.isFunction(c)&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")===0&&(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)(d=p._data(g[h],a+"queueHooks"))&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)~f.indexOf(" "+b[g]+" ")||(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,k,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=[].slice.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click")){g=p(this),g.context=this;for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){i={},k=[],g[0]=f;for(d=0;d<q;d++)l=o[d],m=l.selector,i[m]===b&&(i[m]=g.is(m)),i[m]&&k.push(l);k.length&&u.push({elem:f,matches:k})}}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){j=u[d],c.currentTarget=j.elem;for(e=0;e<j.matches.length&&!c.isImmediatePropagationStopped();e++){l=j.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,h=((p.event.special[l.origType]||{}).handle||l.handler).apply(j.elem,r),h!==b&&(c.result=h,h===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{ready:{setup:p.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)Z(a,b[e],c,d)}function be(a,b,c,d,e,f){var g,h=$.setFilters[b.toLowerCase()];return h||Z.error(b),(a||!(g=e))&&bd(a||"*",d,g=[],e),g.length>0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;a<c;a++)arguments[a]===b&&(g[a]=b)};for(;p<q;p++){s.exec(""),a=f[p],j=[],i=0,k=e;while(g=s.exec(a)){n=s.lastIndex=g.index+g[0].length;if(n>i){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="<a name='"+q+"'></a><div name='"+q+"'></div>",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},odd:function(a,b,c){var d=[],e=c?0:1,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},lt:function(a,b,c){return c?a.slice(+b):a.slice(0,+b)},gt:function(a,b,c){return c?a.slice(0,+b+1):a.slice(+b+1)},eq:function(a,b,c){var d=a.splice(+b,1);return c?a:d}}};$.setFilters.nth=$.setFilters.eq,$.filters=$.pseudos,X||($.attrHandle={href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}}),V&&($.order.push("NAME"),$.find.NAME=function(a,b){if(typeof b.getElementsByName!==j)return b.getElementsByName(a)}),Y&&($.order.splice(1,0,"CLASS"),$.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!==j&&!c)return b.getElementsByClassName(a)});try{n.call(i.childNodes,0)[0].nodeType}catch(_){n=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}var ba=Z.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},bb=Z.contains=i.compareDocumentPosition?function(a,b){return!!(a.compareDocumentPosition(b)&16)}:i.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc=Z.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=bc(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=bc(b);return c};Z.attr=function(a,b){var c,d=ba(a);return d||(b=b.toLowerCase()),$.attrHandle[b]?$.attrHandle[b](a):U||d?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},Z.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},[0,0].sort(function(){return l=0}),i.compareDocumentPosition?e=function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:(e=function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],g=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return f(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)g.unshift(j),j=j.parentNode;c=e.length,d=g.length;for(var l=0;l<c&&l<d;l++)if(e[l]!==g[l])return f(e[l],g[l]);return l===c?f(a,g[l],-1):f(e[l],b,1)},f=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),Z.uniqueSort=function(a){var b,c=1;if(e){k=l,a.sort(e);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1)}return a};var bl=Z.compile=function(a,b,c){var d,e,f,g=O[a];if(g&&g.context===b)return g;e=bg(a,b,c);for(f=0;d=e[f];f++)e[f]=bj(d,b,c);return g=O[a]=bk(e),g.context=b,g.runs=g.dirruns=0,P.push(a),P.length>$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j<k;j++){p=$.order[j];if(s=L[p].exec(m)){h=$.find[p]((s[1]||"").replace(K,""),q,g);if(h==null)continue;m===r&&(a=a.slice(0,a.length-r.length)+m.replace(L[p],""),a||o.apply(e,n.call(h,0)));break}}}if(a){i=bl(a,b,g),d=i.dirruns++,h==null&&(h=$.find.TAG("*",G.test(a)&&b.parentNode||b));for(j=0;l=h[j];j++)c=i.runs++,i(l,b)&&e.push(l)}return e};h.querySelectorAll&&function(){var a,b=bm,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[],f=[":active"],g=i.matchesSelector||i.mozMatchesSelector||i.webkitMatchesSelector||i.oMatchesSelector||i.msMatchesSelector;T(function(a){a.innerHTML="<select><option selected></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=(c[0]||c).ownerDocument||c[0]||c,typeof c.createDocumentFragment=="undefined"&&(c=e),a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cS[c]=cS[c]||[],cS[c].unshift(b)},prefilter:function(a,b){b?cR.unshift(a):cR.push(a)}}),p.Tween=cY,cY.prototype={constructor:cY,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cY.propHooks[this.prop];return a&&a.get?a.get(this):cY.propHooks._default.get(this)},run:function(a){var b,c=cY.propHooks[this.prop];return this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration),this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cY.propHooks._default.set(this),this}},cY.prototype.init.prototype=cY.prototype,cY.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cY.propHooks.scrollTop=cY.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(cZ(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bY).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cV(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cQ.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:cZ("show"),slideUp:cZ("hide"),slideToggle:cZ("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cY.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cN&&(cN=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cN),cN=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c$=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j,k,l,m=this[0],n=m&&m.ownerDocument;if(!n)return;return(e=n.body)===m?p.offset.bodyOffset(m):(d=n.documentElement,p.contains(d,m)?(c=m.getBoundingClientRect(),f=c_(n),g=d.clientTop||e.clientTop||0,h=d.clientLeft||e.clientLeft||0,i=f.pageYOffset||d.scrollTop,j=f.pageXOffset||d.scrollLeft,k=c.top+i-g,l=c.left+j-h,{top:k,left:l}):{top:0,left:0})},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window);
|
src/components/hero/info/Parameters.js | DragonLegend/game | import React from 'react';
import capitalize from 'capitalize';
import { connect } from 'react-redux';
import { increaseParameter } from '../../../actions/heroActions';
function select(state) {
return { hero: state.hero };
}
export default connect(select)(({ hero, dispatch }) => {
function renderFeature(orig, feature) {
let output = '';
if (orig - feature === 0) {
return output;
}
output += ' [';
if (feature > orig) {
output += '+';
}
output += feature - orig;
output += ']';
return output;
}
return (
<div className="uk-panel uk-panel-box">
<h3 className="uk-panel-title">Parameters</h3>
<div className="uk-grid">
{['strength', 'dexterity', 'intuition', 'health'].map((parameter) => {
const parameterCap = capitalize(parameter);
return [
<div className="uk-width-4-10">{parameterCap}</div>,
<div className="uk-width-4-10">
{hero[parameter]} {renderFeature(hero[parameter], hero.feature[parameter])}
</div>,
<div className="uk-width-1-10">
{hero.numberOfParameters ?
(
<a
onClick={() => dispatch(increaseParameter(parameter))}
className="uk-icon-hover uk-icon-plus-circle"
/>
) : null}
</div>,
];
})}
</div>
{hero.numberOfParameters ?
<div className="uk-margin-small-top">To increase: {hero.numberOfParameters}</div> : null}
</div>
);
});
|
modules/gui/src/widget/elementResizeDetector.js | openforis/sepal | import {Subject, concat, debounceTime, distinctUntilChanged, first} from 'rxjs'
import {compose} from 'compose'
import PropTypes from 'prop-types'
import React from 'react'
import ReactResizeDetector from 'react-resize-detector'
import withSubscriptions from 'subscription'
const UPDATE_DEBOUNCE_MS = 250
export class _ElementResizeDetector extends React.Component {
size$ = new Subject()
render() {
const {children} = this.props
return (
<ReactResizeDetector
handleHeight
handleWidth
onResize={(width, height) => this.size$.next({width, height})}>
{children || null}
</ReactResizeDetector>
)
}
componentDidMount() {
const {debounce, onResize, addSubscription} = this.props
const firstImmediate$ = this.size$.pipe(
first()
)
const subsequentDebounced$ = this.size$.pipe(
debounceTime(debounce)
)
const resize$ = concat(
firstImmediate$,
subsequentDebounced$
).pipe(
distinctUntilChanged()
)
addSubscription(
resize$.subscribe(
({width, height}) => onResize({width, height})
)
)
}
}
export const ElementResizeDetector = compose(
_ElementResizeDetector,
withSubscriptions()
)
ElementResizeDetector.propTypes = {
onResize: PropTypes.func.isRequired,
children: PropTypes.any,
debounce: PropTypes.number
}
ElementResizeDetector.defaultProps = {
debounce: UPDATE_DEBOUNCE_MS
}
|
packages/material-ui-icons/src/FlightLand.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M2.5 19h19v2h-19zm7.18-5.73l4.35 1.16 5.31 1.42c.8.21 1.62-.26 1.84-1.06.21-.8-.26-1.62-1.06-1.84l-5.31-1.42-2.76-9.02L10.12 2v8.28L5.15 8.95l-.93-2.32-1.45-.39v5.17l1.6.43 5.31 1.43z" /></g>
, 'FlightLand');
|
client/index.js | bjoberg/social-pulse | /**
* Client entry point
*/
import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import App from './App';
import store from './store';
import { checkLogin } from './actions/user';
// Moved initializing of store to store.js
// NOTE: this removes functionality for server-side Redux state intialization
// const store = configureStore(window.__INITIAL_STATE__);
const mountApp = document.getElementById('root');
// initialize store with user login every App render (i.e. when page is first loaded/refreshed)
store.dispatch(checkLogin());
render(
<AppContainer>
<App store={store} />
</AppContainer>,
mountApp
);
// For hot reloading of react components
if (module.hot) {
module.hot.accept('./App', () => {
// If you use Webpack 2 in ES modules mode, you can
// use <App /> here rather than require() a <NextApp />.
const NextApp = require('./App').default; // eslint-disable-line global-require
render(
<AppContainer>
<NextApp store={store} />
</AppContainer>,
mountApp
);
});
}
|
examples/todo/js/components/TodoListFooter.js | almasakchabayev/relay | /**
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// IndexLink isn't exported in main package on React Router 1.0.0-rc1.
import IndexLink from 'react-router/lib/IndexLink';
import Link from 'react-router/lib/Link';
import RemoveCompletedTodosMutation from '../mutations/RemoveCompletedTodosMutation';
import React from 'react';
import Relay from 'react-relay';
class TodoListFooter extends React.Component {
_handleRemoveCompletedTodosClick = () => {
Relay.Store.update(
new RemoveCompletedTodosMutation({
todos: this.props.viewer.todos,
viewer: this.props.viewer,
})
);
}
render() {
var numTodos = this.props.viewer.totalCount;
var numCompletedTodos = this.props.viewer.completedCount;
return (
<footer className="footer">
<span className="todo-count">
<strong>{numTodos}</strong> item{numTodos === 1 ? '' : 's'} left
</span>
<ul className="filters">
<li>
<IndexLink to="/" activeClassName="selected">All</IndexLink>
</li>
<li>
<Link to="/active" activeClassName="selected">Active</Link>
</li>
<li>
<Link to="/completed" activeClassName="selected">Completed</Link>
</li>
</ul>
{numCompletedTodos > 0 &&
<button
className="clear-completed"
onClick={this._handleRemoveCompletedTodosClick}>
Clear completed
</button>
}
</footer>
);
}
}
export default Relay.createContainer(TodoListFooter, {
prepareVariables() {
return {
limit: Number.MAX_SAFE_INTEGER || 9007199254740991,
};
},
fragments: {
viewer: () => Relay.QL`
fragment on User {
completedCount,
todos(status: "completed", first: $limit) {
${RemoveCompletedTodosMutation.getFragment('todos')},
},
totalCount,
${RemoveCompletedTodosMutation.getFragment('viewer')},
}
`,
},
});
|
packages/icons/src/md/hardware/SmartPhone.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdSmartPhone(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M34 2.02c2.21 0 4 1.77 4 3.98v36c0 2.21-1.79 4-4 4H14c-2.21 0-4-1.79-4-4V6c0-2.21 1.79-4 4-4l20 .02zM34 38V10H14v28h20z" />
</IconBase>
);
}
export default MdSmartPhone;
|
client/components/myspaces.js | LivenUp/livenup | import React, { Component } from 'react';
import Planner from '../containers/planner';
export default class Profile extends Component {
render() {
return (
<Planner />
);
}
}
|
ajax/libs/yui/3.17.1/datatable-body/datatable-body.js | ram-nadella/cdnjs | /*
YUI 3.17.1 (build 0eb5a52)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('datatable-body', function (Y, NAME) {
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
@module datatable
@submodule datatable-body
@since 3.5.0
**/
var Lang = Y.Lang,
isArray = Lang.isArray,
isNumber = Lang.isNumber,
isString = Lang.isString,
fromTemplate = Lang.sub,
htmlEscape = Y.Escape.html,
toArray = Y.Array,
bind = Y.bind,
YObject = Y.Object,
valueRegExp = /\{value\}/g,
EV_CONTENT_UPDATE = 'contentUpdate',
shiftMap = {
above: [-1, 0],
below: [1, 0],
next: [0, 1],
prev: [0, -1],
previous: [0, -1]
};
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
Translates the provided `modelList` into a rendered `<tbody>` based on the data
in the constituent Models, altered or amended by any special column
configurations.
The `columns` configuration, passed to the constructor, determines which
columns will be rendered.
The rendering process involves constructing an HTML template for a complete row
of data, built by concatenating a customized copy of the instance's
`CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is
then populated with values from each Model in the `modelList`, aggregating a
complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this
column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform any
custom modifications on the cell or row Node that could not be performed by
`formatter`s. Should be used sparingly for better performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a column.
A column `formatter` can be:
* a function, as described below.
* a string which can be:
* the name of a pre-defined formatter function
which can be located in the `Y.DataTable.BodyView.Formatters` hash using the
value of the `formatter` property as the index.
* A template that can use the `{value}` placeholder to include the value
for the current cell or the name of any field in the underlaying model
also enclosed in curly braces. Any number and type of these placeholders
can be used.
Column `formatter`s are passed an object (`o`) with the following properties:
* `value` - The current value of the column's associated attribute, if any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML content. A
returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`.
When adding content to the cell, prefer appending into this property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as
it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The DOM
elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@class BodyView
@namespace DataTable
@extends View
@since 3.5.0
**/
Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], {
// -- Instance properties -------------------------------------------------
/**
HTML template used to create table cells.
@property CELL_TEMPLATE
@type {String}
@default '<td {headers} class="{className}">{content}</td>'
@since 3.5.0
**/
CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>',
/**
CSS class applied to even rows. This is assigned at instantiation.
For DataTable, this will be `yui3-datatable-even`.
@property CLASS_EVEN
@type {String}
@default 'yui3-table-even'
@since 3.5.0
**/
//CLASS_EVEN: null
/**
CSS class applied to odd rows. This is assigned at instantiation.
When used by DataTable instances, this will be `yui3-datatable-odd`.
@property CLASS_ODD
@type {String}
@default 'yui3-table-odd'
@since 3.5.0
**/
//CLASS_ODD: null
/**
HTML template used to create table rows.
@property ROW_TEMPLATE
@type {String}
@default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>'
@since 3.5.0
**/
ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>',
/**
The object that serves as the source of truth for column and row data.
This property is assigned at instantiation from the `host` property of
the configuration object passed to the constructor.
@property host
@type {Object}
@default (initially unset)
@since 3.5.0
**/
//TODO: should this be protected?
//host: null,
/**
HTML templates used to create the `<tbody>` containing the table rows.
@property TBODY_TEMPLATE
@type {String}
@default '<tbody class="{className}">{content}</tbody>'
@since 3.6.0
**/
TBODY_TEMPLATE: '<tbody class="{className}"></tbody>',
// -- Public methods ------------------------------------------------------
/**
Returns the `<td>` Node from the given row and column index. Alternately,
the `seed` can be a Node. If so, the nearest ancestor cell is returned.
If the `seed` is a cell, it is returned. If there is no cell at the given
coordinates, `null` is returned.
Optionally, include an offset array or string to return a cell near the
cell identified by the `seed`. The offset can be an array containing the
number of rows to shift followed by the number of columns to shift, or one
of "above", "below", "next", or "previous".
<pre><code>// Previous cell in the previous row
var cell = table.getCell(e.target, [-1, -1]);
// Next cell
var cell = table.getCell(e.target, 'next');
var cell = table.getCell(e.target, [0, 1];</pre></code>
@method getCell
@param {Number[]|Node} seed Array of row and column indexes, or a Node that
is either the cell itself or a descendant of one.
@param {Number[]|String} [shift] Offset by which to identify the returned
cell Node
@return {Node}
@since 3.5.0
**/
getCell: function (seed, shift) {
var tbody = this.tbodyNode,
row, cell, index, rowIndexOffset;
if (seed && tbody) {
if (isArray(seed)) {
row = tbody.get('children').item(seed[0]);
cell = row && row.get('children').item(seed[1]);
} else if (seed._node) {
cell = seed.ancestor('.' + this.getClassName('cell'), true);
}
if (cell && shift) {
rowIndexOffset = tbody.get('firstChild.rowIndex');
if (isString(shift)) {
if (!shiftMap[shift]) {
Y.error('Unrecognized shift: ' + shift, null, 'datatable-body');
}
shift = shiftMap[shift];
}
if (isArray(shift)) {
index = cell.get('parentNode.rowIndex') +
shift[0] - rowIndexOffset;
row = tbody.get('children').item(index);
index = cell.get('cellIndex') + shift[1];
cell = row && row.get('children').item(index);
}
}
}
return cell || null;
},
/**
Returns the generated CSS classname based on the input. If the `host`
attribute is configured, it will attempt to relay to its `getClassName`
or use its static `NAME` property as a string base.
If `host` is absent or has neither method nor `NAME`, a CSS classname
will be generated using this class's `NAME`.
@method getClassName
@param {String} token* Any number of token strings to assemble the
classname from.
@return {String}
@protected
@since 3.5.0
**/
getClassName: function () {
var host = this.host,
args;
if (host && host.getClassName) {
return host.getClassName.apply(host, arguments);
} else {
args = toArray(arguments);
args.unshift(this.constructor.NAME);
return Y.ClassNameManager.getClassName
.apply(Y.ClassNameManager, args);
}
},
/**
Returns the Model associated to the row Node or id provided. Passing the
Node or id for a descendant of the row also works.
If no Model can be found, `null` is returned.
@method getRecord
@param {String|Node} seed Row Node or `id`, or one for a descendant of a row
@return {Model}
@since 3.5.0
**/
getRecord: function (seed) {
var modelList = this.get('modelList'),
tbody = this.tbodyNode,
row = null,
record;
if (tbody) {
if (isString(seed)) {
seed = tbody.one('#' + seed);
}
if (seed && seed._node) {
row = seed.ancestor(function (node) {
return node.get('parentNode').compareTo(tbody);
}, true);
record = row &&
modelList.getByClientId(row.getData('yui3-record'));
}
}
return record || null;
},
/**
Returns the `<tr>` Node from the given row index, Model, or Model's
`clientId`. If the rows haven't been rendered yet, or if the row can't be
found by the input, `null` is returned.
@method getRow
@param {Number|String|Model} id Row index, Model instance, or clientId
@return {Node}
@since 3.5.0
**/
getRow: function (id) {
var tbody = this.tbodyNode,
row = null;
if (tbody) {
if (id) {
id = this._idMap[id.get ? id.get('clientId') : id] || id;
}
row = isNumber(id) ?
tbody.get('children').item(id) :
tbody.one('#' + id);
}
return row;
},
/**
Creates the table's `<tbody>` content by assembling markup generated by
populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content
from the `columns` and `modelList` attributes.
The rendering process happens in three stages:
1. A row template is assembled from the `columns` attribute (see
`_createRowTemplate`)
2. An HTML string is built up by concatenating the application of the data in
each Model in the `modelList` to the row template. For cells with
`formatter`s, the function is called to generate cell content. Cells
with `nodeFormatter`s are ignored. For all other cells, the data value
from the Model attribute for the given column key is used. The
accumulated row markup is then inserted into the container.
3. If any column is configured with a `nodeFormatter`, the `modelList` is
iterated again to apply the `nodeFormatter`s.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in
this column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform
any custom modifications on the cell or row Node that could not be
performed by `formatter`s. Should be used sparingly for better
performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a
column.
Column `formatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML
content. A returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the
`<td>`. When adding content to the cell, prefer appending into this
property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`,
as it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The
DOM elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@method render
@chainable
@since 3.5.0
**/
render: function () {
var table = this.get('container'),
data = this.get('modelList'),
displayCols = this.get('columns'),
tbody = this.tbodyNode ||
(this.tbodyNode = this._createTBodyNode());
// Needed for mutation
this._createRowTemplate(displayCols);
if (data) {
tbody.setHTML(this._createDataHTML(displayCols));
this._applyNodeFormatters(tbody, displayCols);
}
if (tbody.get('parentNode') !== table) {
table.appendChild(tbody);
}
this.bindUI();
return this;
},
/**
Refreshes the provided row against the provided model and the Array of
columns to be updated.
@method refreshRow
@param {Node} row
@param {Model} model Y.Model representation of the row
@param {String[]} colKeys Array of column keys
@chainable
*/
refreshRow: function (row, model, colKeys) {
var col,
cell,
len = colKeys.length,
i;
for (i = 0; i < len; i++) {
col = this.getColumn(colKeys[i]);
if (col !== null) {
cell = row.one('.' + this.getClassName('col', col._id || col.key));
this.refreshCell(cell, model);
}
}
return this;
},
/**
Refreshes the given cell with the provided model data and the provided
column configuration.
Uses the provided column formatter if aviable.
@method refreshCell
@param {Node} cell Y.Node pointer to the cell element to be updated
@param {Model} [model] Y.Model representation of the row
@param {Object} [col] Column configuration object for the cell
@chainable
*/
refreshCell: function (cell, model, col) {
var content,
formatterFn,
formatterData,
data = model.toJSON();
cell = this.getCell(cell);
/* jshint -W030 */
model || (model = this.getRecord(cell));
col || (col = this.getColumn(cell));
/* jshint +W030 */
if (col.nodeFormatter) {
formatterData = {
cell: cell.one('.' + this.getClassName('liner')) || cell,
column: col,
data: data,
record: model,
rowIndex: this._getRowIndex(cell.ancestor('tr')),
td: cell,
value: data[col.key]
};
keep = col.nodeFormatter.call(host,formatterData);
if (keep === false) {
// Remove from the Node cache to reduce
// memory footprint. This also purges events,
// which you shouldn't be scoping to a cell
// anyway. You've been warned. Incidentally,
// you should always return false. Just sayin.
cell.destroy(true);
}
} else if (col.formatter) {
if (!col._formatterFn) {
col = this._setColumnsFormatterFn([col])[0];
}
formatterFn = col._formatterFn || null;
if (formatterFn) {
formatterData = {
value : data[col.key],
data : data,
column : col,
record : model,
className: '',
rowClass : '',
rowIndex : this._getRowIndex(cell.ancestor('tr'))
};
// Formatters can either return a value ...
content = formatterFn.call(this.get('host'), formatterData);
// ... or update the value property of the data obj passed
if (content === undefined) {
content = formatterData.value;
}
}
if (content === undefined || content === null || content === '') {
content = col.emptyCellValue || '';
}
} else {
content = data[col.key] || col.emptyCellValue || '';
}
cell.setHTML(col.allowHTML ? content : Y.Escape.html(content));
return this;
},
/**
Returns column data from this.get('columns'). If a Y.Node is provided as
the key, will try to determine the key from the classname
@method getColumn
@param {String|Node} name
@return {Object} Returns column configuration
*/
getColumn: function (name) {
if (name && name._node) {
// get column name from node
name = name.get('className').match(
new RegExp( this.getClassName('col') +'-([^ ]*)' )
)[1];
}
if (this.host) {
return this.host._columnMap[name] || null;
}
var displayCols = this.get('columns'),
col = null;
Y.Array.some(displayCols, function (_col) {
if ((_col._id || _col.key) === name) {
col = _col;
return true;
}
});
return col;
},
// -- Protected and private methods ---------------------------------------
/**
Handles changes in the source's columns attribute. Redraws the table data.
@method _afterColumnsChange
@param {EventFacade} e The `columnsChange` event object
@protected
@since 3.5.0
**/
// TODO: Preserve existing DOM
// This will involve parsing and comparing the old and new column configs
// and reacting to four types of changes:
// 1. formatter, nodeFormatter, emptyCellValue changes
// 2. column deletions
// 3. column additions
// 4. column moves (preserve cells)
_afterColumnsChange: function () {
this.render();
},
/**
Handles modelList changes, including additions, deletions, and updates.
Modifies the existing table DOM accordingly.
@method _afterDataChange
@param {EventFacade} e The `change` event from the ModelList
@protected
@since 3.5.0
**/
_afterDataChange: function (e) {
var type = (e.type.match(/:(add|change|remove)$/) || [])[1],
index = e.index,
displayCols = this.get('columns'),
col,
changed = e.changed && Y.Object.keys(e.changed),
key,
row,
i,
len;
for (i = 0, len = displayCols.length; i < len; i++ ) {
col = displayCols[i];
// since nodeFormatters typcially make changes outside of it's
// cell, we need to see if there are any columns that have a
// nodeFormatter and if so, we need to do a full render() of the
// tbody
if (col.hasOwnProperty('nodeFormatter')) {
this.render();
this.fire(EV_CONTENT_UPDATE);
return;
}
}
// TODO: if multiple rows are being added/remove/swapped, can we avoid the restriping?
switch (type) {
case 'change':
for (i = 0, len = displayCols.length; i < len; i++) {
col = displayCols[i];
key = col.key;
if (col.formatter && !e.changed[key]) {
changed.push(key);
}
}
this.refreshRow(this.getRow(e.target), e.target, changed);
break;
case 'add':
// we need to make sure we don't have an index larger than the data we have
index = Math.min(index, this.get('modelList').size() - 1);
// updates the columns with formatter functions
this._setColumnsFormatterFn(displayCols);
row = Y.Node.create(this._createRowHTML(e.model, index, displayCols));
this.tbodyNode.insert(row, index);
this._restripe(index);
break;
case 'remove':
this.getRow(index).remove(true);
// we removed a row, so we need to back up our index to stripe
this._restripe(index - 1);
break;
default:
this.render();
}
// Event fired to tell users when we are done updating after the data
// was changed
this.fire(EV_CONTENT_UPDATE);
},
/**
Toggles the odd/even classname of the row after the given index. This method
is used to update rows after a row is inserted into or removed from the table.
Note this event is delayed so the table is only restriped once when multiple
rows are updated at one time.
@protected
@method _restripe
@param {Number} [index] Index of row to start restriping after
@since 3.11.0
*/
_restripe: function (index) {
var task = this._restripeTask,
self;
// index|0 to force int, avoid NaN. Math.max() to avoid neg indexes.
index = Math.max((index|0), 0);
if (!task) {
self = this;
this._restripeTask = {
timer: setTimeout(function () {
// Check for self existence before continuing
if (!self || self.get('destroy') || !self.tbodyNode || !self.tbodyNode.inDoc()) {
self._restripeTask = null;
return;
}
var odd = [self.CLASS_ODD, self.CLASS_EVEN],
even = [self.CLASS_EVEN, self.CLASS_ODD],
index = self._restripeTask.index;
self.tbodyNode.get('childNodes')
.slice(index)
.each(function (row, i) { // TODO: each vs batch
row.replaceClass.apply(row, (index + i) % 2 ? even : odd);
});
self._restripeTask = null;
}, 0),
index: index
};
} else {
task.index = Math.min(task.index, index);
}
},
/**
Handles replacement of the modelList.
Rerenders the `<tbody>` contents.
@method _afterModelListChange
@param {EventFacade} e The `modelListChange` event
@protected
@since 3.6.0
**/
_afterModelListChange: function () {
var handles = this._eventHandles;
if (handles.dataChange) {
handles.dataChange.detach();
delete handles.dataChange;
this.bindUI();
}
if (this.tbodyNode) {
this.render();
}
},
/**
Iterates the `modelList`, and calls any `nodeFormatter`s found in the
`columns` param on the appropriate cell Nodes in the `tbody`.
@method _applyNodeFormatters
@param {Node} tbody The `<tbody>` Node whose columns to update
@param {Object[]} displayCols The column configurations
@protected
@since 3.5.0
**/
_applyNodeFormatters: function (tbody, displayCols) {
var host = this.host || this,
data = this.get('modelList'),
formatters = [],
linerQuery = '.' + this.getClassName('liner'),
rows, i, len;
// Only iterate the ModelList again if there are nodeFormatters
for (i = 0, len = displayCols.length; i < len; ++i) {
if (displayCols[i].nodeFormatter) {
formatters.push(i);
}
}
if (data && formatters.length) {
rows = tbody.get('childNodes');
data.each(function (record, index) {
var formatterData = {
data : record.toJSON(),
record : record,
rowIndex : index
},
row = rows.item(index),
i, len, col, key, cells, cell, keep;
if (row) {
cells = row.get('childNodes');
for (i = 0, len = formatters.length; i < len; ++i) {
cell = cells.item(formatters[i]);
if (cell) {
col = formatterData.column = displayCols[formatters[i]];
key = col.key || col.id;
formatterData.value = record.get(key);
formatterData.td = cell;
formatterData.cell = cell.one(linerQuery) || cell;
keep = col.nodeFormatter.call(host,formatterData);
if (keep === false) {
// Remove from the Node cache to reduce
// memory footprint. This also purges events,
// which you shouldn't be scoping to a cell
// anyway. You've been warned. Incidentally,
// you should always return false. Just sayin.
cell.destroy(true);
}
}
}
}
});
}
},
/**
Binds event subscriptions from the UI and the host (if assigned).
@method bindUI
@protected
@since 3.5.0
**/
bindUI: function () {
var handles = this._eventHandles,
modelList = this.get('modelList'),
changeEvent = modelList.model.NAME + ':change';
if (!handles.columnsChange) {
handles.columnsChange = this.after('columnsChange',
bind('_afterColumnsChange', this));
}
if (modelList && !handles.dataChange) {
handles.dataChange = modelList.after(
['add', 'remove', 'reset', changeEvent],
bind('_afterDataChange', this));
}
},
/**
Iterates the `modelList` and applies each Model to the `_rowTemplate`,
allowing any column `formatter` or `emptyCellValue` to override cell
content for the appropriate column. The aggregated HTML string is
returned.
@method _createDataHTML
@param {Object[]} displayCols The column configurations to customize the
generated cell content or class names
@return {String} The markup for all Models in the `modelList`, each applied
to the `_rowTemplate`
@protected
@since 3.5.0
**/
_createDataHTML: function (displayCols) {
var data = this.get('modelList'),
html = '';
if (data) {
data.each(function (model, index) {
html += this._createRowHTML(model, index, displayCols);
}, this);
}
return html;
},
/**
Applies the data of a given Model, modified by any column formatters and
supplemented by other template values to the instance's `_rowTemplate` (see
`_createRowTemplate`). The generated string is then returned.
The data from Model's attributes is fetched by `toJSON` and this data
object is appended with other properties to supply values to {placeholders}
in the template. For a template generated from a Model with 'foo' and 'bar'
attributes, the data object would end up with the following properties
before being used to populate the `_rowTemplate`:
* `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute.
* `foo` - The value to populate the 'foo' column cell content. This
value will be the value stored in the Model's `foo` attribute, or the
result of the column's `formatter` if assigned. If the value is '',
`null`, or `undefined`, and the column's `emptyCellValue` is assigned,
that value will be used.
* `bar` - Same for the 'bar' column cell content.
* `foo-className` - String of CSS classes to apply to the `<td>`.
* `bar-className` - Same.
* `rowClass` - String of CSS classes to apply to the `<tr>`. This
will be the odd/even class per the specified index plus any additional
classes assigned by column formatters (via `o.rowClass`).
Because this object is available to formatters, any additional properties
can be added to fill in custom {placeholders} in the `_rowTemplate`.
@method _createRowHTML
@param {Model} model The Model instance to apply to the row template
@param {Number} index The index the row will be appearing
@param {Object[]} displayCols The column configurations
@return {String} The markup for the provided Model, less any `nodeFormatter`s
@protected
@since 3.5.0
**/
_createRowHTML: function (model, index, displayCols) {
var data = model.toJSON(),
clientId = model.get('clientId'),
values = {
rowId : this._getRowId(clientId),
clientId: clientId,
rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN
},
host = this.host || this,
i, len, col, token, value, formatterData;
for (i = 0, len = displayCols.length; i < len; ++i) {
col = displayCols[i];
value = data[col.key];
token = col._id || col.key;
values[token + '-className'] = '';
if (col._formatterFn) {
formatterData = {
value : value,
data : data,
column : col,
record : model,
className: '',
rowClass : '',
rowIndex : index
};
// Formatters can either return a value
value = col._formatterFn.call(host, formatterData);
// or update the value property of the data obj passed
if (value === undefined) {
value = formatterData.value;
}
values[token + '-className'] = formatterData.className;
values.rowClass += ' ' + formatterData.rowClass;
}
// if the token missing OR is the value a legit value
if (!values.hasOwnProperty(token) || data.hasOwnProperty(col.key)) {
if (value === undefined || value === null || value === '') {
value = col.emptyCellValue || '';
}
values[token] = col.allowHTML ? value : htmlEscape(value);
}
}
// replace consecutive whitespace with a single space
values.rowClass = values.rowClass.replace(/\s+/g, ' ');
return fromTemplate(this._rowTemplate, values);
},
/**
Locates the row within the tbodyNode and returns the found index, or Null
if it is not found in the tbodyNode
@param {Node} row
@return {Number} Index of row in tbodyNode
*/
_getRowIndex: function (row) {
var tbody = this.tbodyNode,
index = 1;
if (tbody && row) {
//if row is not in the tbody, return
if (row.ancestor('tbody') !== tbody) {
return null;
}
// increment until we no longer have a previous node
/*jshint boss: true*/
while (row = row.previous()) { // NOTE: assignment
/*jshint boss: false*/
index++;
}
}
return index;
},
/**
Creates a custom HTML template string for use in generating the markup for
individual table rows with {placeholder}s to capture data from the Models
in the `modelList` attribute or from column `formatter`s.
Assigns the `_rowTemplate` property.
@method _createRowTemplate
@param {Object[]} displayCols Array of column configuration objects
@protected
@since 3.5.0
**/
_createRowTemplate: function (displayCols) {
var html = '',
cellTemplate = this.CELL_TEMPLATE,
i, len, col, key, token, headers, tokenValues, formatter;
this._setColumnsFormatterFn(displayCols);
for (i = 0, len = displayCols.length; i < len; ++i) {
col = displayCols[i];
key = col.key;
token = col._id || key;
formatter = col._formatterFn;
// Only include headers if there are more than one
headers = (col._headers || []).length > 1 ?
'headers="' + col._headers.join(' ') + '"' : '';
tokenValues = {
content : '{' + token + '}',
headers : headers,
className: this.getClassName('col', token) + ' ' +
(col.className || '') + ' ' +
this.getClassName('cell') +
' {' + token + '-className}'
};
if (!formatter && col.formatter) {
tokenValues.content = col.formatter.replace(valueRegExp, tokenValues.content);
}
if (col.nodeFormatter) {
// Defer all node decoration to the formatter
tokenValues.content = '';
}
html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues);
}
this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, {
content: html
});
},
/**
Parses the columns array and defines the column's _formatterFn if there
is a formatter available on the column
@protected
@method _setColumnsFormatterFn
@param {Object[]} displayCols Array of column configuration objects
@return {Object[]} Returns modified displayCols configuration Array
*/
_setColumnsFormatterFn: function (displayCols) {
var Formatters = Y.DataTable.BodyView.Formatters,
formatter,
col,
i,
len;
for (i = 0, len = displayCols.length; i < len; i++) {
col = displayCols[i];
formatter = col.formatter;
if (!col._formatterFn && formatter) {
if (Lang.isFunction(formatter)) {
col._formatterFn = formatter;
} else if (formatter in Formatters) {
col._formatterFn = Formatters[formatter].call(this.host || this, col);
}
}
}
return displayCols;
},
/**
Creates the `<tbody>` node that will store the data rows.
@method _createTBodyNode
@return {Node}
@protected
@since 3.6.0
**/
_createTBodyNode: function () {
return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, {
className: this.getClassName('data')
}));
},
/**
Destroys the instance.
@method destructor
@protected
@since 3.5.0
**/
destructor: function () {
(new Y.EventHandle(YObject.values(this._eventHandles))).detach();
},
/**
Holds the event subscriptions needing to be detached when the instance is
`destroy()`ed.
@property _eventHandles
@type {Object}
@default undefined (initially unset)
@protected
@since 3.5.0
**/
//_eventHandles: null,
/**
Returns the row ID associated with a Model's clientId.
@method _getRowId
@param {String} clientId The Model clientId
@return {String}
@protected
**/
_getRowId: function (clientId) {
return this._idMap[clientId] || (this._idMap[clientId] = Y.guid());
},
/**
Map of Model clientIds to row ids.
@property _idMap
@type {Object}
@protected
**/
//_idMap,
/**
Initializes the instance. Reads the following configuration properties in
addition to the instance attributes:
* `columns` - (REQUIRED) The initial column information
* `host` - The object to serve as source of truth for column info and
for generating class names
@method initializer
@param {Object} config Configuration data
@protected
@since 3.5.0
**/
initializer: function (config) {
this.host = config.host;
this._eventHandles = {
modelListChange: this.after('modelListChange',
bind('_afterModelListChange', this))
};
this._idMap = {};
this.CLASS_ODD = this.getClassName('odd');
this.CLASS_EVEN = this.getClassName('even');
}
/**
The HTML template used to create a full row of markup for a single Model in
the `modelList` plus any customizations defined in the column
configurations.
@property _rowTemplate
@type {String}
@default (initially unset)
@protected
@since 3.5.0
**/
//_rowTemplate: null
},{
/**
Hash of formatting functions for cell contents.
This property can be populated with a hash of formatting functions by the developer
or a set of pre-defined functions can be loaded via the `datatable-formatters` module.
See: [DataTable.BodyView.Formatters](./DataTable.BodyView.Formatters.html)
@property Formatters
@type Object
@since 3.8.0
@static
**/
Formatters: {}
});
}, '3.17.1', {"requires": ["datatable-core", "view", "classnamemanager"]});
|
src/index.js | JorgeHernandez/reduxWorkshop | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
|
docs/app/src/pages/Resources.js | tercenya/compendium | import React from 'react';
import { CondLang, NavMain, PageHeader, PageFooter, A, MFizzIcon, FontAwesomeIcon } from '../components';
const Resources = (props) => {
return (
<div>
<NavMain activePage="resources" />
<PageHeader
title="Resources"
subTitle="" />
<div className="container compendium-container">
<div className="row">
<div className="col-md-12" role="main">
<div className="compendium-section">
<a name='tools'></a>
<h4>Installing langauges</h4>
<table className='table'>
<thead>
<tr>
<th></th>
<th><FontAwesomeIcon icon='windows' /> Windows</th>
<th><FontAwesomeIcon icon='apple' /> Mac</th>
<th>
<MFizzIcon icon='redhat' /> Redhat
/
<MFizzIcon icon='centos' /> Centos
</th>
<th>
<MFizzIcon icon='debian' /> Debian
/
<MFizzIcon icon='ubuntu' /> Ubuntu
</th>
</tr>
</thead>
<tbody>
<tr>
<th className='nobreak'><MFizzIcon icon='ruby' /> Ruby</th>
<td>From <A href='http://rubyinstaller.org/'>rubyinstaller.org</A></td>
<td>Included, or use <A href='http://brew.sh/'>homebrew</A> to install <A href='https://github.com/rbenv/rbenv'>rbenv</A> and <A href='https://github.com/rbenv/ruby-build'>ruby-build</A>.</td>
<td><code>yum install ruby</code></td>
<td><code>apt-get install ruby</code></td>
</tr>
<tr>
<th className='nobreak'><MFizzIcon icon='python' /> Python</th>
<td>From <A href='https://www.python.org/downloads/windows/'>python.org</A></td>
<td>Included</td>
<td><code>yum install python</code></td>
<td><code>apt-get install python</code></td>
</tr>
<tr>
<th className='nobreak'><MFizzIcon icon='php' /> php</th>
<td>From <A href='http://windows.php.net/download#php-7.0'>php.net</A></td>
<td>Included, or <A href='http://php.net/downloads.php'>php.net</A></td>
<td><code>yum install php</code></td>
<td><code>apt-get install php5</code></td>
</tr>
<tr>
<th className='nobreak'><MFizzIcon icon='nodejs' /> nodejs</th>
<td>From <A href='https://nodejs.org/en/download/'>nodejs.org</A></td>
<td>From <A href='https://nodejs.org/en/download/'>nodejs.org</A>, or use <A href='http://brew.sh/'>homebrew</A> to install the <A href='http://blog.teamtreehouse.com/install-node-js-npm-mac'>node</A> package</td>
<td>From <A href='https://nodejs.org/en/download/'>nodejs.org</A>, or add the <A href='https://github.com/nodesource/distributions'>nodesource repo</A> then <code>yum install nodejs</code></td>
<td>From <A href='https://nodejs.org/en/download/'>nodejs.org</A>, or add the <A href='https://github.com/nodesource/distributions'>nodesource repo</A> then <code>apt-get install nodejs</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<PageFooter />
</div>
);
};
export default Resources;
|
src/components/topic/TopicTitle.js | ahonn/v2exRN | import React, { Component } from 'react';
import {
View,
Text,
StyleSheet
} from 'react-native';
class TopicTitle extends Component {
render() {
const { topic } = this.props;
return (
<View style={styles.titleWrapper}>
<Text style={styles.title}>
{topic.title}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
titleWrapper: {
padding: 10,
backgroundColor: '#efefef',
borderRadius: 5,
},
title: {
color: '#0a0a0a',
fontSize: 16
},
});
export default TopicTitle; |
blueprints/componentOLD/files/src/components/__name__/__name__.js | simonghales/mapping | import React from 'react'
import classes from './<%= pascalEntityName %>.scss'
export const <%= pascalEntityName %> = () => (
<div className={classes['<%= pascalEntityName %>']}>
<h1><%= pascalEntityName %></h1>
</div>
)
export default <%= pascalEntityName %>
|
src/components/Pagination.js | MunGell/elemental | var React = require('react');
var classNames = require('classnames');
module.exports = React.createClass({
displayName: 'Pagination',
propTypes: {
className: React.PropTypes.string,
currentPage: React.PropTypes.number.isRequired,
onPageSelect: React.PropTypes.func,
pageSize: React.PropTypes.number.isRequired,
plural: React.PropTypes.string,
singular: React.PropTypes.string,
style: React.PropTypes.object,
total: React.PropTypes.number.isRequired,
limit: React.PropTypes.number
},
renderCount () {
let count = '';
let { currentPage, pageSize, plural, singular, total } = this.props;
if (!total) {
count = 'No ' + (plural || 'records');
} else if (total > pageSize) {
let start = (pageSize * (currentPage - 1)) + 1;
let end = Math.min(start + pageSize - 1, total);
count = `Showing ${start} to ${end} of ${total}`;
} else {
count = 'Showing ' + total;
if (total > 1 && plural) {
count += ' ' + plural;
} else if (total === 1 && singular) {
count += ' ' + singular;
}
}
return (
<div className="Pagination__count">{count}</div>
);
},
onPageSelect (i) {
if (!this.props.onPageSelect) return;
this.props.onPageSelect(i);
},
renderPages () {
if (this.props.total <= this.props.pageSize) return null;
let pages = [];
let { currentPage, pageSize, total, limit } = this.props;
let totalPages = Math.ceil(total / pageSize);
let minPage = 0;
let maxPage = totalPages;
if (limit && (limit < totalPages)) {
limit = Math.floor(limit / 2);
minPage = currentPage - limit - 1;
maxPage = currentPage + limit;
if (minPage < 0) {
maxPage = maxPage - minPage;
minPage = 0;
}
if (maxPage > totalPages) {
minPage = totalPages - 2 * limit - 1;
maxPage = totalPages;
}
}
if (minPage > 0) {
pages.push(<button key={'page_start'} className={'Pagination__list__item'} onClick={() => this.onPageSelect(1)}>...</button>);
}
for (let i = minPage; i < maxPage; i++) {
let page = i + 1;
let current = (page === currentPage);
let className = classNames('Pagination__list__item', {
'is-selected': current
});
/* eslint-disable no-loop-func */
pages.push(<button key={'page_' + page} className={className} onClick={() => this.onPageSelect(page)}>{page}</button>);
/* eslint-enable */
}
if (maxPage < totalPages) {
pages.push(<button key={'page_end'} className={'Pagination__list__item'} onClick={() => this.onPageSelect(totalPages)}>...</button>);
}
return (
<div className="Pagination__list">
{pages}
</div>
);
},
render () {
var className = classNames('Pagination', this.props.className);
return (
<div className={className} style={this.props.style}>
{this.renderCount()}
{this.renderPages()}
</div>
);
}
});
|
files/rxjs/2.5.2/rx.lite.js | afghanistanyn/jsdelivr | // 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'; },
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) {
var len = arr.length, a = new Array(len);
for(var i = 0; i < len; i++) { a[i] = 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 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;
}
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;
}
// 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(); }
};
// Single assignment
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
this.isDisposed = false;
this.current = null;
};
SingleAssignmentDisposable.prototype.getDisposable = function () {
return this.current;
};
SingleAssignmentDisposable.prototype.setDisposable = function (value) {
if (this.current) { throw new Error('Disposable has already been assigned'); }
var shouldDispose = this.isDisposed;
!shouldDispose && (this.current = value);
shouldDispose && value && value.dispose();
};
SingleAssignmentDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
// Multiple assignment disposable
var SerialDisposable = Rx.SerialDisposable = function () {
this.isDisposed = false;
this.current = null;
};
SerialDisposable.prototype.getDisposable = function () {
return this.current;
};
SerialDisposable.prototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
SerialDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !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;
})();
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;
}
/** Determines whether the given object is a scheduler */
Scheduler.isScheduler = function (s) {
return s instanceof Scheduler;
}
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, isScheduler = Scheduler.isScheduler;
(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));
/** 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 SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var scheduleMethod, clearMethod;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else if (!!root.WScript) {
localSetTimeout = function (fn, time) {
root.WScript.Sleep(time);
fn();
};
} 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 if (root.attachEvent) {
root.attachEvent('onmessage', onGlobalPostMessage);
} else {
root.onmessage = onGlobalPostMessage;
}
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 () {
!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), disposable = new SingleAssignmentDisposable();
if (dt === 0) { return scheduler.scheduleWithState(state, action); }
var id = localSetTimeout(function () {
!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);
})();
/**
* 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 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);
};
/**
* 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 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 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 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));
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);
});
};
var EmptyObservable = (function(__super__) {
inherits(EmptyObservable, __super__);
function EmptyObservable(scheduler) {
this.scheduler = scheduler;
__super__.call(this);
}
EmptyObservable.prototype.subscribeCore = function (observer) {
var sink = new EmptySink(observer, this);
return sink.run();
};
function EmptySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
function scheduleItem(s, state) {
state.onCompleted();
}
EmptySink.prototype.run = function () {
return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem);
};
return EmptyObservable;
}(ObservableBase));
/**
* 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 EmptyObservable(scheduler);
};
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)
};
var NeverObservable = (function(__super__) {
inherits(NeverObservable, __super__);
function NeverObservable() {
__super__.call(this);
}
NeverObservable.prototype.subscribeCore = function (observer) {
return disposableEmpty;
};
return NeverObservable;
}(ObservableBase));
/**
* 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 NeverObservable();
};
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);
};
var PairsObservable = (function(__super__) {
inherits(PairsObservable, __super__);
function PairsObservable(obj, scheduler) {
this.obj = obj;
this.keys = Object.keys(obj);
this.scheduler = scheduler;
__super__.call(this);
}
PairsObservable.prototype.subscribeCore = function (observer) {
var sink = new PairsSink(observer, this);
return sink.run();
};
return PairsObservable;
}(ObservableBase));
function PairsSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
PairsSink.prototype.run = function () {
var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length;
function loopRecursive(i, recurse) {
if (i < len) {
var key = keys[i];
observer.onNext([key, obj[key]]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* 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 = currentThreadScheduler);
return new PairsObservable(obj, scheduler);
};
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);
};
var RepeatObservable = (function(__super__) {
inherits(RepeatObservable, __super__);
function RepeatObservable(value, repeatCount, scheduler) {
this.value = value;
this.repeatCount = repeatCount == null ? -1 : repeatCount;
this.scheduler = scheduler;
__super__.call(this);
}
RepeatObservable.prototype.subscribeCore = function (observer) {
var sink = new RepeatSink(observer, this);
return sink.run();
};
return RepeatObservable;
}(ObservableBase));
function RepeatSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RepeatSink.prototype.run = function () {
var observer = this.observer, value = this.parent.value;
function loopRecursive(i, recurse) {
if (i === -1 || i > 0) {
observer.onNext(value);
i > 0 && i--;
}
if (i === 0) { return observer.onCompleted(); }
recurse(i);
}
return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
* @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 new RepeatObservable(value, repeatCount, scheduler);
};
var JustObservable = (function(__super__) {
inherits(JustObservable, __super__);
function JustObservable(value, scheduler) {
this.value = value;
this.scheduler = scheduler;
__super__.call(this);
}
JustObservable.prototype.subscribeCore = function (observer) {
var sink = new JustSink(observer, this);
return sink.run();
};
function JustSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
function scheduleItem(s, state) {
var value = state[0], observer = state[1];
observer.onNext(value);
observer.onCompleted();
}
JustSink.prototype.run = function () {
return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem);
};
return JustObservable;
}(ObservableBase));
/**
* 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 JustObservable(value, scheduler);
};
var ThrowObservable = (function(__super__) {
inherits(ThrowObservable, __super__);
function ThrowObservable(error, scheduler) {
this.error = error;
this.scheduler = scheduler;
__super__.call(this);
}
ThrowObservable.prototype.subscribeCore = function (observer) {
var sink = new ThrowSink(observer, this);
return sink.run();
};
function ThrowSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
function scheduleItem(s, state) {
var error = state[0], observer = state[1];
observer.onError(error);
}
ThrowSink.prototype.run = function () {
return this.parent.scheduler.scheduleWithState([this.parent.error, this.observer], scheduleItem);
};
return ThrowObservable;
}(ObservableBase));
/**
* 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 = Observable.throwException = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new ThrowObservable(error, scheduler);
};
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 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;
});
};
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);
};
/**
* 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);
};
/**
* 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);
};
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; });
};
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 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);
};
/**
* 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();
};
/**
* 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);
});
});
};
/**
* 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);
}
/**
* 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 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));
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);
};
/**
* 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.default);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default 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);
};
/**
* 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);
};
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, scheduler) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue, scheduler);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
return this.subject.request(numberOfItems == null ? -1 : numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue, scheduler) {
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;
this.scheduler = scheduler || currentThreadScheduler;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
} else {
this.queue.push(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(Notification.createOnError(error));
}
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(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};
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this;
this.requestedDisposable = this.scheduler.scheduleWithState(number,
function(s, i) {
var r = self._processRequest(i), remaining = r.numberOfItems;
if (!r.returnValue) {
self.requestedCount = remaining;
self.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
}
});
return this.requestedDisposable;
},
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 {bool} enableQueue truthy value to determine if values should be queued pending the next request
* @param {Scheduler} scheduler determines how the requests will be scheduled
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue, scheduler) {
if (enableQueue && isScheduler(enableQueue)) {
scheduler = enableQueue;
enableQueue = true;
}
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue, scheduler);
};
/**
* 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;
};
/**
* 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);
};
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 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 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));
/**
* 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));
/**
* 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));
|
src/js/containers/Auth/index.js | ClubExpressions/poc-expression.club | import React from 'react';
export default class Auth extends React.Component {
render () {
return (
<div>
{this.props.children}
</div>
);
}
}
|
imports/plugins/included/taxes-taxcloud/server/jobs/taxcodes.js | aeyde/reaction | import { Meteor } from "meteor/meteor";
import { Job } from "/imports/plugins/core/job-collection/lib";
import { Jobs, Packages } from "/lib/collections";
import { Hooks, Logger, Reaction } from "/server/api";
//
// helper to fetch reaction-taxes config
//
function getJobConfig() {
const config = Packages.findOne({
name: "taxes-taxcloud",
shopId: Reaction.getShopId()
});
return config.settings.taxcloud;
}
//
// add job hook for "taxes/fetchTaxCloudTaxCodes"
//
Hooks.Events.add("afterCoreInit", () => {
const config = getJobConfig();
const refreshPeriod = config.refreshPeriod || 0;
const taxCodeUrl = config.taxCodeUrl || "https://taxcloud.net/tic/?format=json";
// set 0 to disable fetchTIC
if (refreshPeriod !== 0) {
Logger.debug(`Adding taxcloud/getTaxCodes to JobControl. Refresh ${refreshPeriod}`);
new Job(Jobs, "taxcloud/getTaxCodes", { url: taxCodeUrl })
.priority("normal")
.retry({
retries: 5,
wait: 60000,
backoff: "exponential" // delay by twice as long for each subsequent retry
})
.repeat({
schedule: Jobs.later.parse.text(refreshPeriod)
})
.save({
// Cancel any jobs of the same type,
// but only if this job repeats forever.
cancelRepeats: true
});
}
});
//
// index imports and
// will trigger job to run
// taxes/fetchTaxCloudTaxCodes
//
export default function () {
Jobs.processJobs(
"taxcloud/getTaxCodes",
{
pollInterval: 30 * 1000,
workTimeout: 180 * 1000
},
(job, callback) => {
Meteor.call("taxcloud/getTaxCodes", (error) => {
if (error) {
if (error.error === "notConfigured") {
Logger.warn(error.message);
job.done(error.message, { repeatId: true });
} else {
job.done(error.toString(), { repeatId: true });
}
} else {
// we should always return "completed" job here, because errors are fine
const success = "Latest TaxCloud TaxCodes were fetched successfully.";
Reaction.Importer.flush();
Logger.debug(success);
job.done(success, { repeatId: true });
}
});
callback();
}
);
}
|
ajax/libs/react/0.5.2/react.js | sh4hin/cdnjs | /**
* React v0.5.2
*/
!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.React=e():"undefined"!=typeof global?global.React=e():"undefined"!=typeof self&&(self.React=e())}(function(){var define,module,exports;
return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule $
* @typechecks
*/
var ge = require("./ge");
var ex = require("./ex");
/**
* Find a node by ID.
*
* If your application code depends on the existence of the element, use $,
* which will throw if the element doesn't exist.
*
* If you're not sure whether or not the element exists, use ge instead, and
* manually check for the element's existence in your application code.
*
* @param {string|DOMDocument|DOMElement|DOMTextNode|Comment} id
* @return {DOMDocument|DOMElement|DOMTextNode|Comment}
*/
function $(id) {
var element = ge(id);
if (!element) {
throw new Error(ex(
'Tried to get element with id of "%s" but it is not present on the page.',
id
));
}
return element;
}
module.exports = $;
},{"./ex":83,"./ge":87}],2:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule CSSProperty
*/
"use strict";
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
fillOpacity: true,
fontWeight: true,
lineHeight: true,
opacity: true,
orphans: true,
zIndex: true,
zoom: true
};
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See http://bugs.jquery.com/ticket/12385.
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundImage: true,
backgroundPosition: true,
backgroundRepeat: true,
backgroundColor: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
},{}],3:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule CSSPropertyOperations
* @typechecks static-only
*/
"use strict";
var CSSProperty = require("./CSSProperty");
var dangerousStyleValue = require("./dangerousStyleValue");
var escapeTextForBrowser = require("./escapeTextForBrowser");
var hyphenate = require("./hyphenate");
var memoizeStringOnly = require("./memoizeStringOnly");
var processStyleName = memoizeStringOnly(function(styleName) {
return escapeTextForBrowser(hyphenate(styleName));
});
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
*
* @param {object} styles
* @return {?string}
*/
createMarkupForStyles: function(styles) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue) + ';';
}
}
return serialized || null;
},
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
setValueForStyles: function(node, styles) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = dangerousStyleValue(styleName, styles[styleName]);
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = CSSProperty.shorthandPropertyExpansions[styleName];
if (expansion) {
// Shorthand property that IE8 won't like unsetting, so unset each
// component to placate it
for (var individualStyleName in expansion) {
style[individualStyleName] = '';
}
} else {
style[styleName] = '';
}
}
}
}
};
module.exports = CSSPropertyOperations;
},{"./CSSProperty":2,"./dangerousStyleValue":80,"./escapeTextForBrowser":82,"./hyphenate":94,"./memoizeStringOnly":103}],4:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule CallbackRegistry
* @typechecks static-only
*/
"use strict";
var listenerBank = {};
/**
* Stores "listeners" by `registrationName`/`id`. There should be at most one
* "listener" per `registrationName`/`id` in the `listenerBank`.
*
* Access listeners via `listenerBank[registrationName][id]`.
*
* @class CallbackRegistry
* @internal
*/
var CallbackRegistry = {
/**
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {?function} listener The callback to store.
*/
putListener: function(id, registrationName, listener) {
var bankForRegistrationName =
listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[id] = listener;
},
/**
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function(id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
return bankForRegistrationName && bankForRegistrationName[id];
},
/**
* Deletes a listener from the registration bank.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function(id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
if (bankForRegistrationName) {
delete bankForRegistrationName[id];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {string} id ID of the DOM element.
*/
deleteAllListeners: function(id) {
for (var registrationName in listenerBank) {
delete listenerBank[registrationName][id];
}
},
/**
* This is needed for tests only. Do not use!
*/
__purge: function() {
listenerBank = {};
}
};
module.exports = CallbackRegistry;
},{}],5:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ChangeEventPlugin
*/
"use strict";
var EventConstants = require("./EventConstants");
var EventPluginHub = require("./EventPluginHub");
var EventPropagators = require("./EventPropagators");
var ExecutionEnvironment = require("./ExecutionEnvironment");
var SyntheticEvent = require("./SyntheticEvent");
var isEventSupported = require("./isEventSupported");
var isTextInputElement = require("./isTextInputElement");
var keyOf = require("./keyOf");
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
change: {
phasedRegistrationNames: {
bubbled: keyOf({onChange: null}),
captured: keyOf({onChangeCapture: null})
}
}
};
/**
* For IE shims
*/
var activeElement = null;
var activeElementID = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
return (
elem.nodeName === 'SELECT' ||
(elem.nodeName === 'INPUT' && elem.type === 'file')
);
}
var doesChangeEventBubble = false;
if (ExecutionEnvironment.canUseDOM) {
// See `handleChange` comment below
doesChangeEventBubble = isEventSupported('change') && (
!('documentMode' in document) || document.documentMode > 8
);
}
function manualDispatchChangeEvent(nativeEvent) {
var event = SyntheticEvent.getPooled(
eventTypes.change,
activeElementID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
// If change bubbled, we'd just bind to it like all the other events
// and have it go through ReactEventTopLevelCallback. Since it doesn't, we
// manually listen for the change event and so we have to enqueue and
// process the abstract event manually.
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue();
}
function startWatchingForChangeEventIE8(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementID = null;
}
function getTargetIDForChangeEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topChange) {
return topLevelTargetID;
}
}
function handleEventsForChangeEventIE8(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForChangeEventIE8();
startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForChangeEventIE8();
}
}
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = false;
if (ExecutionEnvironment.canUseDOM) {
// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events
isInputEventSupported = isEventSupported('input') && (
!('documentMode' in document) || document.documentMode > 9
);
}
/**
* (For old IE.) Replacement getter/setter for the `value` property that gets
* set on the active element.
*/
var newValueProp = {
get: function() {
return activeElementValueProp.get.call(this);
},
set: function(val) {
// Cast to a string so we can do equality checks.
activeElementValue = '' + val;
activeElementValueProp.set.call(this, val);
}
};
/**
* (For old IE.) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(
target.constructor.prototype,
'value'
);
Object.defineProperty(activeElement, 'value', newValueProp);
activeElement.attachEvent('onpropertychange', handlePropertyChange);
}
/**
* (For old IE.) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
// delete restores the original property definition
delete activeElement.value;
activeElement.detachEvent('onpropertychange', handlePropertyChange);
activeElement = null;
activeElementID = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For old IE.) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
var value = nativeEvent.srcElement.value;
if (value === activeElementValue) {
return;
}
activeElementValue = value;
manualDispatchChangeEvent(nativeEvent);
}
/**
* If a `change` event should be fired, returns the target's ID.
*/
function getTargetIDForInputEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topInput) {
// In modern browsers (i.e., not IE8 or IE9), the input event is exactly
// what we want so fall through here and trigger an abstract event
return topLevelTargetID;
}
}
// For IE8 and IE9.
function handleEventsForInputEventIE(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// In IE8, we can capture almost all .value changes by adding a
// propertychange handler and looking for events with propertyName
// equal to 'value'
// In IE9, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();
startWatchingForValueChange(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetIDForInputEventIE(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topSelectionChange ||
topLevelType === topLevelTypes.topKeyUp ||
topLevelType === topLevelTypes.topKeyDown) {
// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
if (activeElement && activeElement.value !== activeElementValue) {
activeElementValue = activeElement.value;
return activeElementID;
}
}
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
return (
elem.nodeName === 'INPUT' &&
(elem.type === 'checkbox' || elem.type === 'radio')
);
}
function getTargetIDForClickEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topClick) {
return topLevelTargetID;
}
}
/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/
var ChangeEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var getTargetIDFunc, handleEventFunc;
if (shouldUseChangeEvent(topLevelTarget)) {
if (doesChangeEventBubble) {
getTargetIDFunc = getTargetIDForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(topLevelTarget)) {
if (isInputEventSupported) {
getTargetIDFunc = getTargetIDForInputEvent;
} else {
getTargetIDFunc = getTargetIDForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(topLevelTarget)) {
getTargetIDFunc = getTargetIDForClickEvent;
}
if (getTargetIDFunc) {
var targetID = getTargetIDFunc(
topLevelType,
topLevelTarget,
topLevelTargetID
);
if (targetID) {
var event = SyntheticEvent.getPooled(
eventTypes.change,
targetID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(
topLevelType,
topLevelTarget,
topLevelTargetID
);
}
}
};
module.exports = ChangeEventPlugin;
},{"./EventConstants":14,"./EventPluginHub":16,"./EventPropagators":19,"./ExecutionEnvironment":20,"./SyntheticEvent":65,"./isEventSupported":96,"./isTextInputElement":98,"./keyOf":102}],6:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule CompositionEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = require("./EventConstants");
var EventPropagators = require("./EventPropagators");
var ExecutionEnvironment = require("./ExecutionEnvironment");
var ReactInputSelection = require("./ReactInputSelection");
var SyntheticCompositionEvent = require("./SyntheticCompositionEvent");
var getTextContentAccessor = require("./getTextContentAccessor");
var keyOf = require("./keyOf");
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var useCompositionEvent = ExecutionEnvironment.canUseDOM &&
'CompositionEvent' in window;
var topLevelTypes = EventConstants.topLevelTypes;
var currentComposition = null;
// Events and their corresponding property names.
var eventTypes = {
compositionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({onCompositionEnd: null}),
captured: keyOf({onCompositionEndCapture: null})
}
},
compositionStart: {
phasedRegistrationNames: {
bubbled: keyOf({onCompositionStart: null}),
captured: keyOf({onCompositionStartCapture: null})
}
},
compositionUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({onCompositionUpdate: null}),
captured: keyOf({onCompositionUpdateCapture: null})
}
}
};
/**
* Translate native top level events into event types.
*
* @param {string} topLevelType
* @return {object}
*/
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case topLevelTypes.topCompositionStart:
return eventTypes.compositionStart;
case topLevelTypes.topCompositionEnd:
return eventTypes.compositionEnd;
case topLevelTypes.topCompositionUpdate:
return eventTypes.compositionUpdate;
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackStart(topLevelType, nativeEvent) {
return (
topLevelType === topLevelTypes.topKeyDown &&
nativeEvent.keyCode === START_KEYCODE
);
}
/**
* Does our fallback mode think that this event is the end of composition?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topKeyUp:
// Command keys insert or clear IME input.
return (END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1);
case topLevelTypes.topKeyDown:
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return (nativeEvent.keyCode !== START_KEYCODE);
case topLevelTypes.topKeyPress:
case topLevelTypes.topMouseDown:
case topLevelTypes.topBlur:
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Helper class stores information about selection and document state
* so we can figure out what changed at a later date.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this.root = root;
this.startSelection = ReactInputSelection.getSelection(root);
this.startValue = this.getText();
}
/**
* Get current text of input.
*
* @return {string}
*/
FallbackCompositionState.prototype.getText = function() {
return this.root.value || this.root[getTextContentAccessor()];
};
/**
* Text that has changed since the start of composition.
*
* @return {string}
*/
FallbackCompositionState.prototype.getData = function() {
var endValue = this.getText();
var prefixLength = this.startSelection.start;
var suffixLength = this.startValue.length - this.startSelection.end;
return endValue.substr(
prefixLength,
endValue.length - suffixLength - prefixLength
);
};
/**
* This plugin creates `onCompositionStart`, `onCompositionUpdate` and
* `onCompositionEnd` events on inputs, textareas and contentEditable
* nodes.
*/
var CompositionEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var eventType;
var data;
if (useCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackStart(topLevelType, nativeEvent)) {
eventType = eventTypes.start;
currentComposition = new FallbackCompositionState(topLevelTarget);
}
} else if (isFallbackEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
data = currentComposition.getData();
currentComposition = null;
}
if (eventType) {
var event = SyntheticCompositionEvent.getPooled(
eventType,
topLevelTargetID,
nativeEvent
);
if (data) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = data;
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
};
module.exports = CompositionEventPlugin;
},{"./EventConstants":14,"./EventPropagators":19,"./ExecutionEnvironment":20,"./ReactInputSelection":46,"./SyntheticCompositionEvent":64,"./getTextContentAccessor":93,"./keyOf":102}],7:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule DOMChildrenOperations
* @typechecks static-only
*/
"use strict";
var Danger = require("./Danger");
var ReactMultiChildUpdateTypes = require("./ReactMultiChildUpdateTypes");
var getTextContentAccessor = require("./getTextContentAccessor");
/**
* The DOM property to use when setting text content.
*
* @type {string}
* @private
*/
var textContentAccessor = getTextContentAccessor() || 'NA';
/**
* Inserts `childNode` as a child of `parentNode` at the `index`.
*
* @param {DOMElement} parentNode Parent node in which to insert.
* @param {DOMElement} childNode Child node to insert.
* @param {number} index Index at which to insert the child.
* @internal
*/
function insertChildAt(parentNode, childNode, index) {
var childNodes = parentNode.childNodes;
if (childNodes[index] === childNode) {
return;
}
// If `childNode` is already a child of `parentNode`, remove it so that
// computing `childNodes[index]` takes into account the removal.
if (childNode.parentNode === parentNode) {
parentNode.removeChild(childNode);
}
if (index >= childNodes.length) {
parentNode.appendChild(childNode);
} else {
parentNode.insertBefore(childNode, childNodes[index]);
}
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
/**
* Updates a component's children by processing a series of updates. The
* update configurations are each expected to have a `parentNode` property.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markupList List of markup strings.
* @internal
*/
processUpdates: function(updates, markupList) {
var update;
// Mapping from parent IDs to initial child orderings.
var initialChildren = null;
// List of children that will be moved or removed.
var updatedChildren = null;
for (var i = 0; update = updates[i]; i++) {
if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING ||
update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) {
var updatedIndex = update.fromIndex;
var updatedChild = update.parentNode.childNodes[updatedIndex];
var parentID = update.parentID;
initialChildren = initialChildren || {};
initialChildren[parentID] = initialChildren[parentID] || [];
initialChildren[parentID][updatedIndex] = updatedChild;
updatedChildren = updatedChildren || [];
updatedChildren.push(updatedChild);
}
}
var renderedMarkup = Danger.dangerouslyRenderMarkup(markupList);
// Remove updated children first so that `toIndex` is consistent.
if (updatedChildren) {
for (var j = 0; j < updatedChildren.length; j++) {
updatedChildren[j].parentNode.removeChild(updatedChildren[j]);
}
}
for (var k = 0; update = updates[k]; k++) {
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertChildAt(
update.parentNode,
renderedMarkup[update.markupIndex],
update.toIndex
);
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
insertChildAt(
update.parentNode,
initialChildren[update.parentID][update.fromIndex],
update.toIndex
);
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
update.parentNode[textContentAccessor] = update.textContent;
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
// Already removed by the for-loop above.
break;
}
}
}
};
module.exports = DOMChildrenOperations;
},{"./Danger":10,"./ReactMultiChildUpdateTypes":52,"./getTextContentAccessor":93}],8:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule DOMProperty
* @typechecks static-only
*/
/*jslint bitwise: true */
"use strict";
var invariant = require("./invariant");
var DOMPropertyInjection = {
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
MUST_USE_ATTRIBUTE: 0x1,
MUST_USE_PROPERTY: 0x2,
HAS_BOOLEAN_VALUE: 0x4,
HAS_SIDE_EFFECTS: 0x8,
/**
* Inject some specialized knowledge about the DOM. This takes a config object
* with the following properties:
*
* isCustomAttribute: function that given an attribute name will return true
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
* attributes where it's impossible to enumerate all of the possible
* attribute names,
*
* Properties: object mapping DOM property name to one of the
* DOMPropertyInjection constants or null. If your attribute isn't in here,
* it won't get written to the DOM.
*
* DOMAttributeNames: object mapping React attribute name to the DOM
* attribute name. Attribute names not specified use the **lowercase**
* normalized name.
*
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
* Property names not specified use the normalized name.
*
* DOMMutationMethods: Properties that require special mutation methods. If
* `value` is undefined, the mutation method should unset the property.
*
* @param {object} domPropertyConfig the config as described above.
*/
injectDOMPropertyConfig: function(domPropertyConfig) {
var Properties = domPropertyConfig.Properties || {};
var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
if (domPropertyConfig.isCustomAttribute) {
DOMProperty._isCustomAttributeFunctions.push(
domPropertyConfig.isCustomAttribute
);
}
for (var propName in Properties) {
invariant(
!DOMProperty.isStandardName[propName],
'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' +
'\'%s\' which has already been injected. You may be accidentally ' +
'injecting the same DOM property config twice, or you may be ' +
'injecting two configs that have conflicting property names.',
propName
);
DOMProperty.isStandardName[propName] = true;
var lowerCased = propName.toLowerCase();
DOMProperty.getPossibleStandardName[lowerCased] = propName;
var attributeName = DOMAttributeNames[propName];
if (attributeName) {
DOMProperty.getPossibleStandardName[attributeName] = propName;
}
DOMProperty.getAttributeName[propName] = attributeName || lowerCased;
DOMProperty.getPropertyName[propName] =
DOMPropertyNames[propName] || propName;
var mutationMethod = DOMMutationMethods[propName];
if (mutationMethod) {
DOMProperty.getMutationMethod[propName] = mutationMethod;
}
var propConfig = Properties[propName];
DOMProperty.mustUseAttribute[propName] =
propConfig & DOMPropertyInjection.MUST_USE_ATTRIBUTE;
DOMProperty.mustUseProperty[propName] =
propConfig & DOMPropertyInjection.MUST_USE_PROPERTY;
DOMProperty.hasBooleanValue[propName] =
propConfig & DOMPropertyInjection.HAS_BOOLEAN_VALUE;
DOMProperty.hasSideEffects[propName] =
propConfig & DOMPropertyInjection.HAS_SIDE_EFFECTS;
invariant(
!DOMProperty.mustUseAttribute[propName] ||
!DOMProperty.mustUseProperty[propName],
'DOMProperty: Cannot use require using both attribute and property: %s',
propName
);
invariant(
DOMProperty.mustUseProperty[propName] ||
!DOMProperty.hasSideEffects[propName],
'DOMProperty: Properties that have side effects must use property: %s',
propName
);
}
}
};
var defaultValueCache = {};
/**
* DOMProperty exports lookup objects that can be used like functions:
*
* > DOMProperty.isValid['id']
* true
* > DOMProperty.isValid['foobar']
* undefined
*
* Although this may be confusing, it performs better in general.
*
* @see http://jsperf.com/key-exists
* @see http://jsperf.com/key-missing
*/
var DOMProperty = {
/**
* Checks whether a property name is a standard property.
* @type {Object}
*/
isStandardName: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties.
* @type {Object}
*/
getPossibleStandardName: {},
/**
* Mapping from normalized names to attribute names that differ. Attribute
* names are used when rendering markup or with `*Attribute()`.
* @type {Object}
*/
getAttributeName: {},
/**
* Mapping from normalized names to properties on DOM node instances.
* (This includes properties that mutate due to external factors.)
* @type {Object}
*/
getPropertyName: {},
/**
* Mapping from normalized names to mutation methods. This will only exist if
* mutation cannot be set simply by the property or `setAttribute()`.
* @type {Object}
*/
getMutationMethod: {},
/**
* Whether the property must be accessed and mutated as an object property.
* @type {Object}
*/
mustUseAttribute: {},
/**
* Whether the property must be accessed and mutated using `*Attribute()`.
* (This includes anything that fails `<propName> in <element>`.)
* @type {Object}
*/
mustUseProperty: {},
/**
* Whether the property should be removed when set to a falsey value.
* @type {Object}
*/
hasBooleanValue: {},
/**
* Whether or not setting a value causes side effects such as triggering
* resources to be loaded or text selection changes. We must ensure that
* the value is only set if it has changed.
* @type {Object}
*/
hasSideEffects: {},
/**
* All of the isCustomAttribute() functions that have been injected.
*/
_isCustomAttributeFunctions: [],
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: function(attributeName) {
return DOMProperty._isCustomAttributeFunctions.some(
function(isCustomAttributeFn) {
return isCustomAttributeFn.call(null, attributeName);
}
);
},
/**
* Returns the default property value for a DOM property (i.e., not an
* attribute). Most default values are '' or false, but not all. Worse yet,
* some (in particular, `type`) vary depending on the type of element.
*
* TODO: Is it better to grab all the possible properties when creating an
* element to avoid having to create the same element twice?
*/
getDefaultValueForProperty: function(nodeName, prop) {
var nodeDefaults = defaultValueCache[nodeName];
var testElement;
if (!nodeDefaults) {
defaultValueCache[nodeName] = nodeDefaults = {};
}
if (!(prop in nodeDefaults)) {
testElement = document.createElement(nodeName);
nodeDefaults[prop] = testElement[prop];
}
return nodeDefaults[prop];
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
},{"./invariant":95}],9:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule DOMPropertyOperations
* @typechecks static-only
*/
"use strict";
var DOMProperty = require("./DOMProperty");
var escapeTextForBrowser = require("./escapeTextForBrowser");
var memoizeStringOnly = require("./memoizeStringOnly");
var processAttributeNameAndPrefix = memoizeStringOnly(function(name) {
return escapeTextForBrowser(name) + '="';
});
if (true) {
var reactProps = {
__owner__: true,
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true
};
var warnedProperties = {};
var warnUnknownProperty = function(name) {
if (reactProps[name] || warnedProperties[name]) {
return;
}
warnedProperties[name] = true;
var lowerCasedName = name.toLowerCase();
// data-* attributes should be lowercase; suggest the lowercase version
var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ?
lowerCasedName : DOMProperty.getPossibleStandardName[lowerCasedName];
// For now, only warn when we have a suggested correction. This prevents
// logging too much when using transferPropsTo.
if (standardName != null) {
console.warn(
'Unknown DOM property ' + name + '. Did you mean ' + standardName + '?'
);
}
};
}
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function(name, value) {
if (DOMProperty.isStandardName[name]) {
if (value == null || DOMProperty.hasBooleanValue[name] && !value) {
return '';
}
var attributeName = DOMProperty.getAttributeName[name];
return processAttributeNameAndPrefix(attributeName) +
escapeTextForBrowser(value) + '"';
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return processAttributeNameAndPrefix(name) +
escapeTextForBrowser(value) + '"';
} else if (true) {
warnUnknownProperty(name);
}
return null;
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function(node, name, value) {
if (DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, value);
} else if (DOMProperty.mustUseAttribute[name]) {
if (DOMProperty.hasBooleanValue[name] && !value) {
node.removeAttribute(DOMProperty.getAttributeName[name]);
} else {
node.setAttribute(DOMProperty.getAttributeName[name], '' + value);
}
} else {
var propName = DOMProperty.getPropertyName[name];
if (!DOMProperty.hasSideEffects[name] || node[propName] !== value) {
node[propName] = value;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.setAttribute(name, '' + value);
} else if (true) {
warnUnknownProperty(name);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function(node, name) {
if (DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (DOMProperty.mustUseAttribute[name]) {
node.removeAttribute(DOMProperty.getAttributeName[name]);
} else {
var propName = DOMProperty.getPropertyName[name];
node[propName] = DOMProperty.getDefaultValueForProperty(
node.nodeName,
name
);
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
} else if (true) {
warnUnknownProperty(name);
}
}
};
module.exports = DOMPropertyOperations;
},{"./DOMProperty":8,"./escapeTextForBrowser":82,"./memoizeStringOnly":103}],10:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule Danger
* @typechecks static-only
*/
/*jslint evil: true, sub: true */
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
var createNodesFromMarkup = require("./createNodesFromMarkup");
var emptyFunction = require("./emptyFunction");
var getMarkupWrap = require("./getMarkupWrap");
var invariant = require("./invariant");
var mutateHTMLNodeWithMarkup = require("./mutateHTMLNodeWithMarkup");
var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/;
var RESULT_INDEX_ATTR = 'data-danger-index';
/**
* Extracts the `nodeName` from a string of markup.
*
* NOTE: Extracting the `nodeName` does not require a regular expression match
* because we make assumptions about React-generated markup (i.e. there are no
* spaces surrounding the opening tag and there is at least one attribute).
*
* @param {string} markup String of markup.
* @return {string} Node name of the supplied markup.
* @see http://jsperf.com/extract-nodename
*/
function getNodeName(markup) {
return markup.substring(1, markup.indexOf(' '));
}
var Danger = {
/**
* Renders markup into an array of nodes. The markup is expected to render
* into a list of root nodes. Also, the length of `resultList` and
* `markupList` should be the same.
*
* @param {array<string>} markupList List of markup strings to render.
* @return {array<DOMElement>} List of rendered nodes.
* @internal
*/
dangerouslyRenderMarkup: function(markupList) {
invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyRenderMarkup(...): Cannot render markup in a Worker ' +
'thread. This is likely a bug in the framework. Please report ' +
'immediately.'
);
var nodeName;
var markupByNodeName = {};
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var i = 0; i < markupList.length; i++) {
invariant(
markupList[i],
'dangerouslyRenderMarkup(...): Missing markup.'
);
nodeName = getNodeName(markupList[i]);
nodeName = getMarkupWrap(nodeName) ? nodeName : '*';
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [];
markupByNodeName[nodeName][i] = markupList[i];
}
var resultList = [];
var resultListAssignmentCount = 0;
for (nodeName in markupByNodeName) {
if (!markupByNodeName.hasOwnProperty(nodeName)) {
continue;
}
var markupListByNodeName = markupByNodeName[nodeName];
// This for-in loop skips the holes of the sparse array. The order of
// iteration should follow the order of assignment, which happens to match
// numerical index order, but we don't rely on that.
for (var resultIndex in markupListByNodeName) {
if (markupListByNodeName.hasOwnProperty(resultIndex)) {
var markup = markupListByNodeName[resultIndex];
// Push the requested markup with an additional RESULT_INDEX_ATTR
// attribute. If the markup does not start with a < character, it
// will be discarded below (with an appropriate console.error).
markupListByNodeName[resultIndex] = markup.replace(
OPEN_TAG_NAME_EXP,
// This index will be parsed back out below.
'$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '
);
}
}
// Render each group of markup with similar wrapping `nodeName`.
var renderNodes = createNodesFromMarkup(
markupListByNodeName.join(''),
emptyFunction // Do nothing special with <script> tags.
);
for (i = 0; i < renderNodes.length; ++i) {
var renderNode = renderNodes[i];
if (renderNode.hasAttribute &&
renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
renderNode.removeAttribute(RESULT_INDEX_ATTR);
invariant(
!resultList.hasOwnProperty(resultIndex),
'Danger: Assigning to an already-occupied result index.'
);
resultList[resultIndex] = renderNode;
// This should match resultList.length and markupList.length when
// we're done.
resultListAssignmentCount += 1;
} else if (true) {
console.error(
"Danger: Discarding unexpected node:",
renderNode
);
}
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
invariant(
resultListAssignmentCount === resultList.length,
'Danger: Did not assign to every index of resultList.'
);
invariant(
resultList.length === markupList.length,
'Danger: Expected markup to render %s nodes, but rendered %s.',
markupList.length,
resultList.length
);
return resultList;
},
/**
* Replaces a node with a string of markup at its current position within its
* parent. The markup must render into a single root node.
*
* @param {DOMElement} oldChild Child node to replace.
* @param {string} markup Markup to render in place of the child node.
* @internal
*/
dangerouslyReplaceNodeWithMarkup: function(oldChild, markup) {
invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' +
'worker thread. This is likely a bug in the framework. Please report ' +
'immediately.'
);
invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.');
// createNodesFromMarkup() won't work if the markup is rooted by <html>
// since it has special semantic meaning. So we use an alternatie strategy.
if (oldChild.tagName.toLowerCase() === 'html') {
mutateHTMLNodeWithMarkup(oldChild, markup);
return;
}
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
}
};
module.exports = Danger;
},{"./ExecutionEnvironment":20,"./createNodesFromMarkup":78,"./emptyFunction":81,"./getMarkupWrap":90,"./invariant":95,"./mutateHTMLNodeWithMarkup":108}],11:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule DefaultDOMPropertyConfig
*/
/*jslint bitwise: true*/
"use strict";
var DOMProperty = require("./DOMProperty");
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var DefaultDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(
/^(data|aria)-[a-z_][a-z\d_.\-]*$/
),
Properties: {
/**
* Standard Properties
*/
accept: null,
accessKey: null,
action: null,
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
allowTransparency: MUST_USE_ATTRIBUTE,
alt: null,
autoComplete: null,
autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
className: MUST_USE_PROPERTY,
colSpan: null,
content: null,
contentEditable: null,
contextMenu: MUST_USE_ATTRIBUTE,
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
frameBorder: MUST_USE_ATTRIBUTE,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
href: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
label: null,
lang: null,
list: null,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
method: null,
min: null,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rowSpan: null,
scrollLeft: MUST_USE_PROPERTY,
scrollTop: MUST_USE_PROPERTY,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
size: null,
spellCheck: null,
src: null,
step: null,
style: null,
tabIndex: null,
target: null,
title: null,
type: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
autoCapitalize: null, // Supported in Mobile Safari for keyboard hints
/**
* SVG Properties
*/
cx: MUST_USE_ATTRIBUTE,
cy: MUST_USE_ATTRIBUTE,
d: MUST_USE_ATTRIBUTE,
fill: MUST_USE_ATTRIBUTE,
fx: MUST_USE_ATTRIBUTE,
fy: MUST_USE_ATTRIBUTE,
gradientTransform: MUST_USE_ATTRIBUTE,
gradientUnits: MUST_USE_ATTRIBUTE,
offset: MUST_USE_ATTRIBUTE,
points: MUST_USE_ATTRIBUTE,
r: MUST_USE_ATTRIBUTE,
rx: MUST_USE_ATTRIBUTE,
ry: MUST_USE_ATTRIBUTE,
spreadMethod: MUST_USE_ATTRIBUTE,
stopColor: MUST_USE_ATTRIBUTE,
stopOpacity: MUST_USE_ATTRIBUTE,
stroke: MUST_USE_ATTRIBUTE,
strokeLinecap: MUST_USE_ATTRIBUTE,
strokeWidth: MUST_USE_ATTRIBUTE,
transform: MUST_USE_ATTRIBUTE,
version: MUST_USE_ATTRIBUTE,
viewBox: MUST_USE_ATTRIBUTE,
x1: MUST_USE_ATTRIBUTE,
x2: MUST_USE_ATTRIBUTE,
x: MUST_USE_ATTRIBUTE,
y1: MUST_USE_ATTRIBUTE,
y2: MUST_USE_ATTRIBUTE,
y: MUST_USE_ATTRIBUTE
},
DOMAttributeNames: {
className: 'class',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
htmlFor: 'for',
spreadMethod: 'spreadMethod',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeLinecap: 'stroke-linecap',
strokeWidth: 'stroke-width',
viewBox: 'viewBox'
},
DOMPropertyNames: {
autoCapitalize: 'autocapitalize',
autoComplete: 'autocomplete',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
encType: 'enctype',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck'
},
DOMMutationMethods: {
/**
* Setting `className` to null may cause it to be set to the string "null".
*
* @param {DOMElement} node
* @param {*} value
*/
className: function(node, value) {
node.className = value || '';
}
}
};
module.exports = DefaultDOMPropertyConfig;
},{"./DOMProperty":8}],12:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule DefaultEventPluginOrder
*/
"use strict";
var keyOf = require("./keyOf");
/**
* Module that is injectable into `EventPluginHub`, that specifies a
* deterministic ordering of `EventPlugin`s. A convenient way to reason about
* plugins, without having to package every one of them. This is better than
* having plugins be ordered in the same order that they are injected because
* that ordering would be influenced by the packaging order.
* `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
* preventing default on events is convenient in `SimpleEventPlugin` handlers.
*/
var DefaultEventPluginOrder = [
keyOf({ResponderEventPlugin: null}),
keyOf({SimpleEventPlugin: null}),
keyOf({TapEventPlugin: null}),
keyOf({EnterLeaveEventPlugin: null}),
keyOf({ChangeEventPlugin: null}),
keyOf({SelectEventPlugin: null}),
keyOf({CompositionEventPlugin: null}),
keyOf({AnalyticsEventPlugin: null}),
keyOf({MobileSafariClickEventPlugin: null})
];
module.exports = DefaultEventPluginOrder;
},{"./keyOf":102}],13:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EnterLeaveEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = require("./EventConstants");
var EventPropagators = require("./EventPropagators");
var SyntheticMouseEvent = require("./SyntheticMouseEvent");
var ReactMount = require("./ReactMount");
var keyOf = require("./keyOf");
var topLevelTypes = EventConstants.topLevelTypes;
var getFirstReactDOM = ReactMount.getFirstReactDOM;
var eventTypes = {
mouseEnter: {registrationName: keyOf({onMouseEnter: null})},
mouseLeave: {registrationName: keyOf({onMouseLeave: null})}
};
var extractedEvents = [null, null];
var EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
if (topLevelType === topLevelTypes.topMouseOver &&
(nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (topLevelType !== topLevelTypes.topMouseOut &&
topLevelType !== topLevelTypes.topMouseOver) {
// Must not be a mouse in or mouse out - ignoring.
return null;
}
var from, to;
if (topLevelType === topLevelTypes.topMouseOut) {
from = topLevelTarget;
to =
getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) ||
window;
} else {
from = window;
to = topLevelTarget;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var fromID = from ? ReactMount.getID(from) : '';
var toID = to ? ReactMount.getID(to) : '';
var leave = SyntheticMouseEvent.getPooled(
eventTypes.mouseLeave,
fromID,
nativeEvent
);
var enter = SyntheticMouseEvent.getPooled(
eventTypes.mouseEnter,
toID,
nativeEvent
);
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID);
extractedEvents[0] = leave;
extractedEvents[1] = enter;
return extractedEvents;
}
};
module.exports = EnterLeaveEventPlugin;
},{"./EventConstants":14,"./EventPropagators":19,"./ReactMount":49,"./SyntheticMouseEvent":68,"./keyOf":102}],14:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventConstants
*/
"use strict";
var keyMirror = require("./keyMirror");
var PropagationPhases = keyMirror({bubbled: null, captured: null});
/**
* Types of raw signals from the browser caught at the top level.
*/
var topLevelTypes = keyMirror({
topBlur: null,
topChange: null,
topClick: null,
topCompositionEnd: null,
topCompositionStart: null,
topCompositionUpdate: null,
topCopy: null,
topCut: null,
topDoubleClick: null,
topDrag: null,
topDragEnd: null,
topDragEnter: null,
topDragExit: null,
topDragLeave: null,
topDragOver: null,
topDragStart: null,
topDrop: null,
topFocus: null,
topInput: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topPaste: null,
topScroll: null,
topSelectionChange: null,
topSubmit: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null,
topWheel: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
},{"./keyMirror":101}],15:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventListener
*/
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listens to bubbled events on a DOM node.
*
* @param {Element} el DOM element to register listener on.
* @param {string} handlerBaseName 'click'/'mouseover'
* @param {Function!} cb Callback function
*/
listen: function(el, handlerBaseName, cb) {
if (el.addEventListener) {
el.addEventListener(handlerBaseName, cb, false);
} else if (el.attachEvent) {
el.attachEvent('on' + handlerBaseName, cb);
}
},
/**
* Listens to captured events on a DOM node.
*
* @see `EventListener.listen` for params.
* @throws Exception if addEventListener is not supported.
*/
capture: function(el, handlerBaseName, cb) {
if (!el.addEventListener) {
if (true) {
console.error(
'You are attempting to use addEventlistener ' +
'in a browser that does not support it support it.' +
'This likely means that you will not receive events that ' +
'your application relies on (such as scroll).');
}
return;
} else {
el.addEventListener(handlerBaseName, cb, true);
}
}
};
module.exports = EventListener;
},{}],16:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventPluginHub
*/
"use strict";
var CallbackRegistry = require("./CallbackRegistry");
var EventPluginRegistry = require("./EventPluginRegistry");
var EventPluginUtils = require("./EventPluginUtils");
var EventPropagators = require("./EventPropagators");
var ExecutionEnvironment = require("./ExecutionEnvironment");
var accumulate = require("./accumulate");
var forEachAccumulated = require("./forEachAccumulated");
var invariant = require("./invariant");
/**
* Internal queue of events that have accumulated their dispatches and are
* waiting to have their dispatches executed.
*/
var eventQueue = null;
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} event Synthetic event to be dispatched.
* @private
*/
var executeDispatchesAndRelease = function(event) {
if (event) {
var executeDispatch = EventPluginUtils.executeDispatch;
// Plugins can provide custom behavior when dispatching events.
var PluginModule = EventPluginRegistry.getPluginModuleForEvent(event);
if (PluginModule && PluginModule.executeDispatch) {
executeDispatch = PluginModule.executeDispatch;
}
EventPluginUtils.executeDispatchesInOrder(event, executeDispatch);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
};
/**
* This is a unified interface for event plugins to be installed and configured.
*
* Event plugins can implement the following properties:
*
* `extractEvents` {function(string, DOMEventTarget, string, object): *}
* Required. When a top-level event is fired, this method is expected to
* extract synthetic events that will in turn be queued and dispatched.
*
* `eventTypes` {object}
* Optional, plugins that fire events must publish a mapping of registration
* names that are used to register listeners. Values of this mapping must
* be objects that contain `registrationName` or `phasedRegistrationNames`.
*
* `executeDispatch` {function(object, function, string)}
* Optional, allows plugins to override how an event gets dispatched. By
* default, the listener is simply invoked.
*
* Each plugin that is injected into `EventsPluginHub` is immediately operable.
*
* @public
*/
var EventPluginHub = {
/**
* Methods for injecting dependencies.
*/
injection: {
/**
* @param {object} InjectedInstanceHandle
* @public
*/
injectInstanceHandle: EventPropagators.injection.injectInstanceHandle,
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
registrationNames: EventPluginRegistry.registrationNames,
putListener: CallbackRegistry.putListener,
getListener: CallbackRegistry.getListener,
deleteListener: CallbackRegistry.deleteListener,
deleteAllListeners: CallbackRegistry.deleteAllListeners,
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0, l = plugins.length; i < l; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
);
if (extractedEvents) {
events = accumulate(events, extractedEvents);
}
}
}
return events;
},
/**
* Enqueues a synthetic event that should be dispatched when
* `processEventQueue` is invoked.
*
* @param {*} events An accumulation of synthetic events.
* @internal
*/
enqueueEvents: function(events) {
if (events) {
eventQueue = accumulate(eventQueue, events);
}
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function() {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
forEachAccumulated(processingEventQueue, executeDispatchesAndRelease);
invariant(
!eventQueue,
'processEventQueue(): Additional events were enqueued while processing ' +
'an event queue. Support for this has not yet been implemented.'
);
}
};
if (ExecutionEnvironment.canUseDOM) {
window.EventPluginHub = EventPluginHub;
}
module.exports = EventPluginHub;
},{"./CallbackRegistry":4,"./EventPluginRegistry":17,"./EventPluginUtils":18,"./EventPropagators":19,"./ExecutionEnvironment":20,"./accumulate":74,"./forEachAccumulated":86,"./invariant":95}],17:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventPluginRegistry
* @typechecks static-only
*/
"use strict";
var invariant = require("./invariant");
/**
* Injectable ordering of event plugins.
*/
var EventPluginOrder = null;
/**
* Injectable mapping from names to event plugin modules.
*/
var namesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering() {
if (!EventPluginOrder) {
// Wait until an `EventPluginOrder` is injected.
return;
}
for (var pluginName in namesToPlugins) {
var PluginModule = namesToPlugins[pluginName];
var pluginIndex = EventPluginOrder.indexOf(pluginName);
invariant(
pluginIndex > -1,
'EventPluginRegistry: Cannot inject event plugins that do not exist in ' +
'the plugin ordering, `%s`.',
pluginName
);
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
invariant(
PluginModule.extractEvents,
'EventPluginRegistry: Event plugins must implement an `extractEvents` ' +
'method, but `%s` does not.',
pluginName
);
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
invariant(
publishEventForPlugin(publishedEvents[eventName], PluginModule),
'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.',
eventName,
pluginName
);
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(dispatchConfig, PluginModule) {
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) {
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(phasedRegistrationName, PluginModule);
}
}
return true;
} else if (dispatchConfig.registrationName) {
publishRegistrationName(dispatchConfig.registrationName, PluginModule);
return true;
}
return false;
}
/**
* Publishes a registration name that is used to identify dispatched events and
* can be used with `EventPluginHub.putListener` to register listeners.
*
* @param {string} registrationName Registration name to add.
* @param {object} PluginModule Plugin publishing the event.
* @private
*/
function publishRegistrationName(registrationName, PluginModule) {
invariant(
!EventPluginRegistry.registrationNames[registrationName],
'EventPluginHub: More than one plugin attempted to publish the same ' +
'registration name, `%s`.',
registrationName
);
EventPluginRegistry.registrationNames[registrationName] = PluginModule;
EventPluginRegistry.registrationNamesKeys.push(registrationName);
}
/**
* Registers plugins so that they can extract and dispatch events.
*
* @see {EventPluginHub}
*/
var EventPluginRegistry = {
/**
* Ordered list of injected plugins.
*/
plugins: [],
/**
* Mapping from registration names to plugin modules.
*/
registrationNames: {},
/**
* The keys of `registrationNames`.
*/
registrationNamesKeys: [],
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
* @see {EventPluginHub.injection.injectEventPluginOrder}
*/
injectEventPluginOrder: function(InjectedEventPluginOrder) {
invariant(
!EventPluginOrder,
'EventPluginRegistry: Cannot inject event plugin ordering more than once.'
);
// Clone the ordering so it cannot be dynamically mutated.
EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder);
recomputePluginOrdering();
},
/**
* Injects plugins to be used by `EventPluginHub`. The plugin names must be
* in the ordering injected by `injectEventPluginOrder`.
*
* Plugins can be injected as part of page initialization or on-the-fly.
*
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
* @internal
* @see {EventPluginHub.injection.injectEventPluginsByName}
*/
injectEventPluginsByName: function(injectedNamesToPlugins) {
var isOrderingDirty = false;
for (var pluginName in injectedNamesToPlugins) {
if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
continue;
}
var PluginModule = injectedNamesToPlugins[pluginName];
if (namesToPlugins[pluginName] !== PluginModule) {
invariant(
!namesToPlugins[pluginName],
'EventPluginRegistry: Cannot inject two different event plugins ' +
'using the same name, `%s`.',
pluginName
);
namesToPlugins[pluginName] = PluginModule;
isOrderingDirty = true;
}
}
if (isOrderingDirty) {
recomputePluginOrdering();
}
},
/**
* Looks up the plugin for the supplied event.
*
* @param {object} event A synthetic event.
* @return {?object} The plugin that created the supplied event.
* @internal
*/
getPluginModuleForEvent: function(event) {
var dispatchConfig = event.dispatchConfig;
if (dispatchConfig.registrationName) {
return EventPluginRegistry.registrationNames[
dispatchConfig.registrationName
] || null;
}
for (var phase in dispatchConfig.phasedRegistrationNames) {
if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNames[
dispatchConfig.phasedRegistrationNames[phase]
];
if (PluginModule) {
return PluginModule;
}
}
return null;
},
/**
* Exposed for unit testing.
* @private
*/
_resetEventPlugins: function() {
EventPluginOrder = null;
for (var pluginName in namesToPlugins) {
if (namesToPlugins.hasOwnProperty(pluginName)) {
delete namesToPlugins[pluginName];
}
}
EventPluginRegistry.plugins.length = 0;
var registrationNames = EventPluginRegistry.registrationNames;
for (var registrationName in registrationNames) {
if (registrationNames.hasOwnProperty(registrationName)) {
delete registrationNames[registrationName];
}
}
EventPluginRegistry.registrationNamesKeys.length = 0;
}
};
module.exports = EventPluginRegistry;
},{"./invariant":95}],18:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventPluginUtils
*/
"use strict";
var EventConstants = require("./EventConstants");
var invariant = require("./invariant");
var topLevelTypes = EventConstants.topLevelTypes;
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp ||
topLevelType === topLevelTypes.topTouchEnd ||
topLevelType === topLevelTypes.topTouchCancel;
}
function isMoveish(topLevelType) {
return topLevelType === topLevelTypes.topMouseMove ||
topLevelType === topLevelTypes.topTouchMove;
}
function isStartish(topLevelType) {
return topLevelType === topLevelTypes.topMouseDown ||
topLevelType === topLevelTypes.topTouchStart;
}
var validateEventDispatches;
if (true) {
validateEventDispatches = function(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
var listenersIsArr = Array.isArray(dispatchListeners);
var idsIsArr = Array.isArray(dispatchIDs);
var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0;
var listenersLen = listenersIsArr ?
dispatchListeners.length :
dispatchListeners ? 1 : 0;
invariant(
idsIsArr === listenersIsArr && IDsLen === listenersLen,
'EventPluginUtils: Invalid `event`.'
);
};
}
/**
* Invokes `cb(event, listener, id)`. Avoids using call if no scope is
* provided. The `(listener,id)` pair effectively forms the "dispatch" but are
* kept separate to conserve memory.
*/
function forEachEventDispatch(event, cb) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if (true) {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
cb(event, dispatchListeners[i], dispatchIDs[i]);
}
} else if (dispatchListeners) {
cb(event, dispatchListeners, dispatchIDs);
}
}
/**
* Default implementation of PluginModule.executeDispatch().
* @param {SyntheticEvent} SyntheticEvent to handle
* @param {function} Application-level callback
* @param {string} domID DOM id to pass to the callback.
*/
function executeDispatch(event, listener, domID) {
listener(event, domID);
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, executeDispatch) {
forEachEventDispatch(event, executeDispatch);
event._dispatchListeners = null;
event._dispatchIDs = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return id of the first dispatch execution who's listener returns true, or
* null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrue(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if (true) {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchIDs[i])) {
return dispatchIDs[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchIDs)) {
return dispatchIDs;
}
}
return null;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return The return value of executing the single dispatch.
*/
function executeDirectDispatch(event) {
if (true) {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchID = event._dispatchIDs;
invariant(
!Array.isArray(dispatchListener),
'executeDirectDispatch(...): Invalid `event`.'
);
var res = dispatchListener ?
dispatchListener(event, dispatchID) :
null;
event._dispatchListeners = null;
event._dispatchIDs = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {bool} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(event) {
return !!event._dispatchListeners;
}
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
executeDirectDispatch: executeDirectDispatch,
hasDispatches: hasDispatches,
executeDispatch: executeDispatch
};
module.exports = EventPluginUtils;
},{"./EventConstants":14,"./invariant":95}],19:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventPropagators
*/
"use strict";
var CallbackRegistry = require("./CallbackRegistry");
var EventConstants = require("./EventConstants");
var accumulate = require("./accumulate");
var forEachAccumulated = require("./forEachAccumulated");
var getListener = CallbackRegistry.getListener;
var PropagationPhases = EventConstants.PropagationPhases;
/**
* Injected dependencies:
*/
/**
* - `InstanceHandle`: [required] Module that performs logical traversals of DOM
* hierarchy given ids of the logical DOM elements involved.
*/
var injection = {
InstanceHandle: null,
injectInstanceHandle: function(InjectedInstanceHandle) {
injection.InstanceHandle = InjectedInstanceHandle;
if (true) {
injection.validate();
}
},
validate: function() {
var invalid = !injection.InstanceHandle||
!injection.InstanceHandle.traverseTwoPhase ||
!injection.InstanceHandle.traverseEnterLeave;
if (invalid) {
throw new Error('InstanceHandle not injected before use!');
}
}
};
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(id, event, propagationPhase) {
var registrationName =
event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(id, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(domID, upwards, event) {
if (true) {
if (!domID) {
throw new Error('Dispatching id must not be null');
}
injection.validate();
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(domID, event, phase);
if (listener) {
event._dispatchListeners = accumulate(event._dispatchListeners, listener);
event._dispatchIDs = accumulate(event._dispatchIDs, domID);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We can not perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
injection.InstanceHandle.traverseTwoPhase(
event.dispatchMarker,
accumulateDirectionalDispatches,
event
);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(id, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(id, registrationName);
if (listener) {
event._dispatchListeners = accumulate(event._dispatchListeners, listener);
event._dispatchIDs = accumulate(event._dispatchIDs, id);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event.dispatchMarker, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
if (true) {
injection.validate();
}
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
if (true) {
injection.validate();
}
injection.InstanceHandle.traverseEnterLeave(
fromID,
toID,
accumulateDispatches,
leave,
enter
);
}
function accumulateDirectDispatches(events) {
if (true) {
injection.validate();
}
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches,
injection: injection
};
module.exports = EventPropagators;
},{"./CallbackRegistry":4,"./EventConstants":14,"./accumulate":74,"./forEachAccumulated":86}],20:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ExecutionEnvironment
*/
/*jslint evil: true */
"use strict";
var canUseDOM = typeof window !== 'undefined';
/**
* 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',
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
},{}],21:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule LinkedValueMixin
* @typechecks static-only
*/
"use strict";
var invariant = require("./invariant");
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueMixin = {
_assertLink: function() {
invariant(
this.props.value == null && this.props.onChange == null,
'Cannot provide a valueLink and a value or onChange event. If you ' +
'want to use value or onChange, you probably don\'t want to use ' +
'valueLink'
);
},
/**
* @return {*} current value of the input either from value prop or link.
*/
getValue: function() {
if (this.props.valueLink) {
this._assertLink();
return this.props.valueLink.value;
}
return this.props.value;
},
/**
* @return {function} change callback either from onChange prop or link.
*/
getOnChange: function() {
if (this.props.valueLink) {
this._assertLink();
return this._handleLinkedValueChange;
}
return this.props.onChange;
},
/**
* @param {SyntheticEvent} e change event to handle
*/
_handleLinkedValueChange: function(e) {
this.props.valueLink.requestChange(e.target.value);
}
};
module.exports = LinkedValueMixin;
},{"./invariant":95}],22:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule MobileSafariClickEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = require("./EventConstants");
var emptyFunction = require("./emptyFunction");
var topLevelTypes = EventConstants.topLevelTypes;
/**
* Mobile Safari does not fire properly bubble click events on non-interactive
* elements, which means delegated click listeners do not fire. The workaround
* for this bug involves attaching an empty click listener on the target node.
*
* This particular plugin works around the bug by attaching an empty click
* listener on `touchstart` (which does fire on every element).
*/
var MobileSafariClickEventPlugin = {
eventTypes: null,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
if (topLevelType === topLevelTypes.topTouchStart) {
var target = nativeEvent.target;
if (target && !target.onclick) {
target.onclick = emptyFunction;
}
}
}
};
module.exports = MobileSafariClickEventPlugin;
},{"./EventConstants":14,"./emptyFunction":81}],23:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule PooledClass
*/
"use strict";
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function(copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function(a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function(a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var fiveArgumentPooler = function(a1, a2, a3, a4, a5) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4, a5);
return instance;
} else {
return new Klass(a1, a2, a3, a4, a5);
}
};
var standardReleaser = function(instance) {
var Klass = this;
if (instance.destructor) {
instance.destructor();
}
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances (optional).
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function(CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
},{}],24:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule React
*/
"use strict";
var ReactComponent = require("./ReactComponent");
var ReactCompositeComponent = require("./ReactCompositeComponent");
var ReactCurrentOwner = require("./ReactCurrentOwner");
var ReactDOM = require("./ReactDOM");
var ReactDOMComponent = require("./ReactDOMComponent");
var ReactDefaultInjection = require("./ReactDefaultInjection");
var ReactInstanceHandles = require("./ReactInstanceHandles");
var ReactMount = require("./ReactMount");
var ReactMultiChild = require("./ReactMultiChild");
var ReactPerf = require("./ReactPerf");
var ReactPropTypes = require("./ReactPropTypes");
var ReactServerRendering = require("./ReactServerRendering");
var ReactTextComponent = require("./ReactTextComponent");
ReactDefaultInjection.inject();
var React = {
DOM: ReactDOM,
PropTypes: ReactPropTypes,
initializeTouchEvents: function(shouldUseTouch) {
ReactMount.useTouchEvents = shouldUseTouch;
},
createClass: ReactCompositeComponent.createClass,
constructAndRenderComponent: ReactMount.constructAndRenderComponent,
constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
renderComponent: ReactPerf.measure(
'React',
'renderComponent',
ReactMount.renderComponent
),
renderComponentToString: ReactServerRendering.renderComponentToString,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
unmountAndReleaseReactRootNode: ReactMount.unmountAndReleaseReactRootNode,
isValidClass: ReactCompositeComponent.isValidClass,
isValidComponent: ReactComponent.isValidComponent,
__internals: {
Component: ReactComponent,
CurrentOwner: ReactCurrentOwner,
DOMComponent: ReactDOMComponent,
InstanceHandles: ReactInstanceHandles,
Mount: ReactMount,
MultiChild: ReactMultiChild,
TextComponent: ReactTextComponent
}
};
// Version exists only in the open-source version of React, not in Facebook's
// internal version.
React.version = '0.5.2';
module.exports = React;
},{"./ReactComponent":25,"./ReactCompositeComponent":28,"./ReactCurrentOwner":29,"./ReactDOM":30,"./ReactDOMComponent":32,"./ReactDefaultInjection":41,"./ReactInstanceHandles":47,"./ReactMount":49,"./ReactMultiChild":51,"./ReactPerf":54,"./ReactPropTypes":56,"./ReactServerRendering":58,"./ReactTextComponent":59}],25:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactComponent
*/
"use strict";
var ReactComponentEnvironment = require("./ReactComponentEnvironment");
var ReactCurrentOwner = require("./ReactCurrentOwner");
var ReactOwner = require("./ReactOwner");
var ReactUpdates = require("./ReactUpdates");
var invariant = require("./invariant");
var keyMirror = require("./keyMirror");
var merge = require("./merge");
/**
* Every React component is in one of these life cycles.
*/
var ComponentLifeCycle = keyMirror({
/**
* Mounted components have a DOM node representation and are capable of
* receiving new props.
*/
MOUNTED: null,
/**
* Unmounted components are inactive and cannot receive new props.
*/
UNMOUNTED: null
});
/**
* Warn if there's no key explicitly set on dynamic arrays of children.
* This allows us to keep track of children between updates.
*/
var ownerHasWarned = {};
/**
* Warn if the component doesn't have an explicit key assigned to it.
* This component is in an array. The array could grow and shrink or be
* reordered. All children, that hasn't already been validated, are required to
* have a "key" property assigned to it.
*
* @internal
* @param {ReactComponent} component Component that requires a key.
*/
function validateExplicitKey(component) {
if (component.__keyValidated__ || component.props.key != null) {
return;
}
component.__keyValidated__ = true;
// We can't provide friendly warnings for top level components.
if (!ReactCurrentOwner.current) {
return;
}
// Name of the component whose render method tried to pass children.
var currentName = ReactCurrentOwner.current.constructor.displayName;
if (ownerHasWarned.hasOwnProperty(currentName)) {
return;
}
ownerHasWarned[currentName] = true;
var message = 'Each child in an array should have a unique "key" prop. ' +
'Check the render method of ' + currentName + '.';
if (!component.isOwnedBy(ReactCurrentOwner.current)) {
// Name of the component that originally created this child.
var childOwnerName =
component.props.__owner__ &&
component.props.__owner__.constructor.displayName;
// Usually the current owner is the offender, but if it accepts
// children as a property, it may be the creator of the child that's
// responsible for assigning it a key.
message += ' It was passed a child from ' + childOwnerName + '.';
}
console.warn(message);
}
/**
* Ensure that every component either is passed in a static location or, if
* if it's passed in an array, has an explicit key property defined.
*
* @internal
* @param {*} component Statically passed child of any type.
* @return {boolean}
*/
function validateChildKeys(component) {
if (Array.isArray(component)) {
for (var i = 0; i < component.length; i++) {
var child = component[i];
if (ReactComponent.isValidComponent(child)) {
validateExplicitKey(child);
}
}
} else if (ReactComponent.isValidComponent(component)) {
// This component was passed in a valid location.
component.__keyValidated__ = true;
}
}
/**
* Components are the basic units of composition in React.
*
* Every component accepts a set of keyed input parameters known as "props" that
* are initialized by the constructor. Once a component is mounted, the props
* can be mutated using `setProps` or `replaceProps`.
*
* Every component is capable of the following operations:
*
* `mountComponent`
* Initializes the component, renders markup, and registers event listeners.
*
* `receiveProps`
* Updates the rendered DOM nodes given a new set of props.
*
* `unmountComponent`
* Releases any resources allocated by this component.
*
* Components can also be "owned" by other components. Being owned by another
* component means being constructed by that component. This is different from
* being the child of a component, which means having a DOM representation that
* is a child of the DOM representation of that component.
*
* @class ReactComponent
*/
var ReactComponent = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
isValidComponent: function(object) {
return !!(
object &&
typeof object.mountComponentIntoNode === 'function' &&
typeof object.receiveProps === 'function'
);
},
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
* @internal
*/
getKey: function(component, index) {
if (component && component.props && component.props.key != null) {
// Explicit key
return '{' + component.props.key + '}';
}
// Implicit key determined by the index in the set
return '[' + index + ']';
},
/**
* @internal
*/
LifeCycle: ComponentLifeCycle,
/**
* Injected module that provides ability to mutate individual properties.
* Injected into the base class because many different subclasses need access
* to this.
*
* @internal
*/
DOMIDOperations: ReactComponentEnvironment.DOMIDOperations,
/**
* Optionally injectable environment dependent cleanup hook. (server vs.
* browser etc). Example: A browser system caches DOM nodes based on component
* ID and must remove that cache entry when this instance is unmounted.
*
* @private
*/
unmountIDFromEnvironment: ReactComponentEnvironment.unmountIDFromEnvironment,
/**
* The "image" of a component tree, is the platform specific (typically
* serialized) data that represents a tree of lower level UI building blocks.
* On the web, this "image" is HTML markup which describes a construction of
* low level `div` and `span` nodes. Other platforms may have different
* encoding of this "image". This must be injected.
*
* @private
*/
mountImageIntoNode: ReactComponentEnvironment.mountImageIntoNode,
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction:
ReactComponentEnvironment.ReactReconcileTransaction,
/**
* Base functionality for every ReactComponent constructor. Mixed into the
* `ReactComponent` prototype, but exposed statically for easy access.
*
* @lends {ReactComponent.prototype}
*/
Mixin: merge(ReactComponentEnvironment.Mixin, {
/**
* Checks whether or not this component is mounted.
*
* @return {boolean} True if mounted, false otherwise.
* @final
* @protected
*/
isMounted: function() {
return this._lifeCycleState === ComponentLifeCycle.MOUNTED;
},
/**
* Sets a subset of the props.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
*/
setProps: function(partialProps, callback) {
// Merge with `_pendingProps` if it exists, otherwise with existing props.
this.replaceProps(
merge(this._pendingProps || this.props, partialProps),
callback
);
},
/**
* Replaces all of the props.
*
* @param {object} props New props.
* @param {?function} callback Called after props are updated.
* @final
* @public
*/
replaceProps: function(props, callback) {
invariant(
!this.props.__owner__,
'replaceProps(...): You called `setProps` or `replaceProps` on a ' +
'component with an owner. This is an anti-pattern since props will ' +
'get reactively updated when rendered. Instead, change the owner\'s ' +
'`render` method to pass the correct value as props to the component ' +
'where it is created.'
);
invariant(
this.isMounted(),
'replaceProps(...): Can only update a mounted component.'
);
this._pendingProps = props;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* Base constructor for all React component.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.construct.call(this, ...)`.
*
* @param {?object} initialProps
* @param {*} children
* @internal
*/
construct: function(initialProps, children) {
this.props = initialProps || {};
// Record the component responsible for creating this component.
this.props.__owner__ = ReactCurrentOwner.current;
// All components start unmounted.
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
this._pendingProps = null;
this._pendingCallbacks = null;
// Children can be more than one argument
var childrenLength = arguments.length - 1;
if (childrenLength === 1) {
if (true) {
validateChildKeys(children);
}
this.props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
if (true) {
validateChildKeys(arguments[i + 1]);
}
childArray[i] = arguments[i + 1];
}
this.props.children = childArray;
}
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* NOTE: This does not insert any nodes into the DOM.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.mountComponent.call(this, ...)`.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy.
* @return {?string} Rendered markup to be inserted into the DOM.
* @internal
*/
mountComponent: function(rootID, transaction, mountDepth) {
invariant(
!this.isMounted(),
'mountComponent(%s, ...): Can only mount an unmounted component.',
rootID
);
var props = this.props;
if (props.ref != null) {
ReactOwner.addComponentAsRefTo(this, props.ref, props.__owner__);
}
this._rootNodeID = rootID;
this._lifeCycleState = ComponentLifeCycle.MOUNTED;
this._mountDepth = mountDepth;
// Effectively: return '';
},
/**
* Releases any resources allocated by `mountComponent`.
*
* NOTE: This does not remove any nodes from the DOM.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.unmountComponent.call(this)`.
*
* @internal
*/
unmountComponent: function() {
invariant(
this.isMounted(),
'unmountComponent(): Can only unmount a mounted component.'
);
var props = this.props;
if (props.ref != null) {
ReactOwner.removeComponentAsRefFrom(this, props.ref, props.__owner__);
}
ReactComponent.unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
},
/**
* Updates the rendered DOM nodes given a new set of props.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.receiveProps.call(this, ...)`.
*
* @param {object} nextProps Next set of properties.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveProps: function(nextProps, transaction) {
invariant(
this.isMounted(),
'receiveProps(...): Can only update a mounted component.'
);
this._pendingProps = nextProps;
this._performUpdateIfNecessary(transaction);
},
/**
* Call `_performUpdateIfNecessary` within a new transaction.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function() {
var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
transaction.perform(this._performUpdateIfNecessary, this, transaction);
ReactComponent.ReactReconcileTransaction.release(transaction);
},
/**
* If `_pendingProps` is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_performUpdateIfNecessary: function(transaction) {
if (this._pendingProps == null) {
return;
}
var prevProps = this.props;
this.props = this._pendingProps;
this._pendingProps = null;
this.updateComponent(transaction, prevProps);
},
/**
* Updates the component's currently mounted representation.
*
* @param {ReactReconcileTransaction} transaction
* @param {object} prevProps
* @internal
*/
updateComponent: function(transaction, prevProps) {
var props = this.props;
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`.
if (props.__owner__ !== prevProps.__owner__ ||
props.ref !== prevProps.ref) {
if (prevProps.ref != null) {
ReactOwner.removeComponentAsRefFrom(
this, prevProps.ref, prevProps.__owner__
);
}
// Correct, even if the owner is the same, and only the ref has changed.
if (props.ref != null) {
ReactOwner.addComponentAsRefTo(this, props.ref, props.__owner__);
}
}
},
/**
* Mounts this component and inserts it into the DOM.
*
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
* @final
* @internal
* @see {ReactMount.renderComponent}
*/
mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) {
var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
transaction.perform(
this._mountComponentIntoNode,
this,
rootID,
container,
transaction,
shouldReuseMarkup
);
ReactComponent.ReactReconcileTransaction.release(transaction);
},
/**
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
* @final
* @private
*/
_mountComponentIntoNode: function(
rootID,
container,
transaction,
shouldReuseMarkup) {
var markup = this.mountComponent(rootID, transaction, 0);
ReactComponent.mountImageIntoNode(markup, container, shouldReuseMarkup);
},
/**
* Checks if this component is owned by the supplied `owner` component.
*
* @param {ReactComponent} owner Component to check.
* @return {boolean} True if `owners` owns this component.
* @final
* @internal
*/
isOwnedBy: function(owner) {
return this.props.__owner__ === owner;
},
/**
* Gets another component, that shares the same owner as this one, by ref.
*
* @param {string} ref of a sibling Component.
* @return {?ReactComponent} the actual sibling Component.
* @final
* @internal
*/
getSiblingByRef: function(ref) {
var owner = this.props.__owner__;
if (!owner || !owner.refs) {
return null;
}
return owner.refs[ref];
}
})
};
module.exports = ReactComponent;
},{"./ReactComponentEnvironment":27,"./ReactCurrentOwner":29,"./ReactOwner":53,"./ReactUpdates":60,"./invariant":95,"./keyMirror":101,"./merge":104}],26:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactComponentBrowserEnvironment
*/
/*jslint evil: true */
"use strict";
var ReactDOMIDOperations = require("./ReactDOMIDOperations");
var ReactMarkupChecksum = require("./ReactMarkupChecksum");
var ReactMount = require("./ReactMount");
var ReactReconcileTransaction = require("./ReactReconcileTransaction");
var getReactRootElementInContainer = require("./getReactRootElementInContainer");
var invariant = require("./invariant");
var mutateHTMLNodeWithMarkup = require("./mutateHTMLNodeWithMarkup");
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
/**
* Abstracts away all functionality of `ReactComponent` requires knowledge of
* the browser context.
*/
var ReactComponentBrowserEnvironment = {
/**
* Mixed into every component instance.
*/
Mixin: {
/**
* Returns the DOM node rendered by this component.
*
* @return {DOMElement} The root node of this component.
* @final
* @protected
*/
getDOMNode: function() {
invariant(
this.isMounted(),
'getDOMNode(): A component must be mounted to have a DOM node.'
);
return ReactMount.getNode(this._rootNodeID);
}
},
ReactReconcileTransaction: ReactReconcileTransaction,
DOMIDOperations: ReactDOMIDOperations,
/**
* If a particular environment requires that some resources be cleaned up,
* specify this in the injected Mixin. In the DOM, we would likely want to
* purge any cached node ID lookups.
*
* @private
*/
unmountIDFromEnvironment: function(rootNodeID) {
ReactMount.purgeID(rootNodeID);
},
/**
* @param {string} markup Markup string to place into the DOM Element.
* @param {DOMElement} container DOM Element to insert markup into.
* @param {boolean} shouldReuseMarkup Should reuse the existing markup in the
* container if possible.
*/
mountImageIntoNode: function(markup, container, shouldReuseMarkup) {
invariant(
container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE && ReactMount.allowFullPageRender
),
'mountComponentIntoNode(...): Target container is not valid.'
);
if (shouldReuseMarkup) {
if (ReactMarkupChecksum.canReuseMarkup(
markup,
getReactRootElementInContainer(container))) {
return;
} else {
if (true) {
console.warn(
'React attempted to use reuse markup in a container but the ' +
'checksum was invalid. This generally means that you are using ' +
'server rendering and the markup generated on the server was ' +
'not what the client was expecting. React injected new markup ' +
'to compensate which works but you have lost many of the ' +
'benefits of server rendering. Instead, figure out why the ' +
'markup being generated is different on the client or server.'
);
}
}
}
// You can't naively set the innerHTML of the entire document. You need
// to mutate documentElement which requires doing some crazy tricks. See
// mutateHTMLNodeWithMarkup()
if (container.nodeType === DOC_NODE_TYPE) {
mutateHTMLNodeWithMarkup(container.documentElement, markup);
return;
}
// Asynchronously inject markup by ensuring that the container is not in
// the document when settings its `innerHTML`.
var parent = container.parentNode;
if (parent) {
var next = container.nextSibling;
parent.removeChild(container);
container.innerHTML = markup;
if (next) {
parent.insertBefore(container, next);
} else {
parent.appendChild(container);
}
} else {
container.innerHTML = markup;
}
}
};
module.exports = ReactComponentBrowserEnvironment;
},{"./ReactDOMIDOperations":34,"./ReactMarkupChecksum":48,"./ReactMount":49,"./ReactReconcileTransaction":57,"./getReactRootElementInContainer":92,"./invariant":95,"./mutateHTMLNodeWithMarkup":108}],27:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactComponentEnvironment
*/
var ReactComponentBrowserEnvironment =
require("./ReactComponentBrowserEnvironment");
var ReactComponentEnvironment = ReactComponentBrowserEnvironment;
module.exports = ReactComponentEnvironment;
},{"./ReactComponentBrowserEnvironment":26}],28:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactCompositeComponent
*/
"use strict";
var ReactComponent = require("./ReactComponent");
var ReactCurrentOwner = require("./ReactCurrentOwner");
var ReactOwner = require("./ReactOwner");
var ReactPerf = require("./ReactPerf");
var ReactPropTransferer = require("./ReactPropTransferer");
var ReactUpdates = require("./ReactUpdates");
var invariant = require("./invariant");
var keyMirror = require("./keyMirror");
var merge = require("./merge");
var mixInto = require("./mixInto");
var objMap = require("./objMap");
/**
* Policies that describe methods in `ReactCompositeComponentInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base ReactCompositeComponent class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
});
/**
* Composite components are higher-level components that compose other composite
* or native components.
*
* To create a new type of `ReactCompositeComponent`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactCompositeComponentInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will available on the prototype.
*
* @interface ReactCompositeComponentInterface
* @internal
*/
var ReactCompositeComponentInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_ONCE,
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: SpecPolicy.DEFINE_ONCE,
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props and state.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props and state will not require a component update.
*
* shouldComponentUpdate: function(nextProps, nextState) {
* return !equal(nextProps, this.props) || !equal(nextState, this.state);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
/**
* Invoked when the component is about to update due to a transition from
* `this.props` and `this.state` to `nextProps` and `nextState`.
*
* 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 {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: SpecPolicy.DEFINE_MANY,
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: SpecPolicy.OVERRIDE_BASE
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared in the specification when defining classes
* using `React.createClass`, they will not be on the component's prototype.
*/
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]);
}
}
},
propTypes: function(Constructor, propTypes) {
Constructor.propTypes = propTypes;
}
};
function validateMethodOverride(proto, name) {
var specPolicy = ReactCompositeComponentInterface[name];
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactCompositeComponentMixin.hasOwnProperty(name)) {
invariant(
specPolicy === SpecPolicy.OVERRIDE_BASE,
'ReactCompositeComponentInterface: You are attempting to override ' +
'`%s` from your class specification. Ensure that your method names ' +
'do not overlap with React methods.',
name
);
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
invariant(
specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED,
'ReactCompositeComponentInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
);
}
}
function validateLifeCycleOnReplaceState(instance) {
var compositeLifeCycleState = instance._compositeLifeCycleState;
invariant(
instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'replaceState(...): Can only update a mounted or mounting component.'
);
invariant(
compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'replaceState(...): Cannot update while unmounting component or during ' +
'an existing state transition (such as within `render`).'
);
}
/**
* Custom version of `mixInto` which handles policy validation and reserved
* specification keys when building `ReactCompositeComponent` classses.
*/
function mixSpecIntoComponent(Constructor, spec) {
var proto = Constructor.prototype;
for (var name in spec) {
var property = spec[name];
if (!spec.hasOwnProperty(name) || !property) {
continue;
}
validateMethodOverride(proto, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactCompositeComponent methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isCompositeComponentMethod = name in ReactCompositeComponentInterface;
var isInherited = name in proto;
var markedDontBind = property.__reactDontBind;
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isCompositeComponentMethod &&
!isInherited &&
!markedDontBind;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isInherited) {
// For methods which are defined more than once, call the existing
// methods before calling the new property.
if (ReactCompositeComponentInterface[name] ===
SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[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 mergeObjectsWithNoDuplicateKeys(one, two) {
invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects'
);
objMap(two, function(value, key) {
invariant(
one[key] === undefined,
'mergeObjectsWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: %s',
key
);
one[key] = value;
});
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
return mergeObjectsWithNoDuplicateKeys(
one.apply(this, arguments),
two.apply(this, arguments)
);
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* `ReactCompositeComponent` maintains an auxiliary life cycle state in
* `this._compositeLifeCycleState` (which can be null).
*
* This is different from the life cycle state maintained by `ReactComponent` in
* `this._lifeCycleState`. The following diagram shows how the states overlap in
* time. There are times when the CompositeLifeCycle is null - at those times it
* is only meaningful to look at ComponentLifeCycle alone.
*
* Top Row: ReactComponent.ComponentLifeCycle
* Low Row: ReactComponent.CompositeLifeCycle
*
* +-------+------------------------------------------------------+--------+
* | UN | MOUNTED | UN |
* |MOUNTED| | MOUNTED|
* +-------+------------------------------------------------------+--------+
* | ^--------+ +------+ +------+ +------+ +--------^ |
* | | | | | | | | | | | |
* | 0--|MOUNTING|-0-|RECEIV|-0-|RECEIV|-0-|RECEIV|-0-| UN |--->0 |
* | | | |PROPS | | PROPS| | STATE| |MOUNTING| |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +--------+ +------+ +------+ +------+ +--------+ |
* | | | |
* +-------+------------------------------------------------------+--------+
*/
var CompositeLifeCycle = keyMirror({
/**
* Components in the process of being mounted respond to state changes
* differently.
*/
MOUNTING: null,
/**
* Components in the process of being unmounted are guarded against state
* changes.
*/
UNMOUNTING: null,
/**
* Components that are mounted and receiving new props respond to state
* changes differently.
*/
RECEIVING_PROPS: null,
/**
* Components that are mounted and receiving new state are guarded against
* additional state changes.
*/
RECEIVING_STATE: null
});
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {?object} initialProps
* @param {*} children
* @final
* @internal
*/
construct: function(initialProps, children) {
// Children can be either an array or more than one argument
ReactComponent.Mixin.construct.apply(this, arguments);
this.state = null;
this._pendingState = null;
this._compositeLifeCycleState = null;
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
return ReactComponent.Mixin.isMounted.call(this) &&
this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: ReactPerf.measure(
'ReactCompositeComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING;
this._defaultProps = this.getDefaultProps ? this.getDefaultProps() : null;
this._processProps(this.props);
if (this.__reactAutoBindMap) {
this._bindAutoBindMethods();
}
this.state = this.getInitialState ? this.getInitialState() : null;
this._pendingState = null;
this._pendingForceUpdate = false;
if (this.componentWillMount) {
this.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingState` without triggering a re-render.
if (this._pendingState) {
this.state = this._pendingState;
this._pendingState = null;
}
}
this._renderedComponent = this._renderValidatedComponent();
// Done with mounting, `setState` will now trigger UI changes.
this._compositeLifeCycleState = null;
var markup = this._renderedComponent.mountComponent(
rootID,
transaction,
mountDepth + 1
);
if (this.componentDidMount) {
transaction.getReactMountReady().enqueue(this, this.componentDidMount);
}
return markup;
}
),
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function() {
this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING;
if (this.componentWillUnmount) {
this.componentWillUnmount();
}
this._compositeLifeCycleState = null;
this._defaultProps = null;
ReactComponent.Mixin.unmountComponent.call(this);
this._renderedComponent.unmountComponent();
this._renderedComponent = null;
if (this.refs) {
this.refs = null;
}
// Some existing components rely on this.props even after they've been
// destroyed (in event handlers).
// TODO: this.props = null;
// TODO: this.state = null;
},
/**
* Sets a subset of the state. Always use this or `replaceState` to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
setState: function(partialState, callback) {
// Merge with `_pendingState` if it exists, otherwise with existing state.
this.replaceState(
merge(this._pendingState || this.state, partialState),
callback
);
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {object} completeState Next state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
replaceState: function(completeState, callback) {
validateLifeCycleOnReplaceState(this);
this._pendingState = completeState;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* Processes props by setting default values for unspecified props and
* asserting that the props are valid.
*
* @param {object} props
* @private
*/
_processProps: function(props) {
var propName;
var defaultProps = this._defaultProps;
for (propName in defaultProps) {
if (!(propName in props)) {
props[propName] = defaultProps[propName];
}
}
var propTypes = this.constructor.propTypes;
if (propTypes) {
var componentName = this.constructor.displayName;
for (propName in propTypes) {
var checkProp = propTypes[propName];
if (checkProp) {
checkProp(props, propName, componentName);
}
}
}
},
performUpdateIfNecessary: function() {
var compositeLifeCycleState = this._compositeLifeCycleState;
// Do not trigger a state transition if we are in the middle of mounting or
// receiving props because both of those will already be doing this.
if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING ||
compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) {
return;
}
ReactComponent.Mixin.performUpdateIfNecessary.call(this);
},
/**
* If any of `_pendingProps`, `_pendingState`, or `_pendingForceUpdate` is
* set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_performUpdateIfNecessary: function(transaction) {
if (this._pendingProps == null &&
this._pendingState == null &&
!this._pendingForceUpdate) {
return;
}
var nextProps = this.props;
if (this._pendingProps != null) {
nextProps = this._pendingProps;
this._processProps(nextProps);
this._pendingProps = null;
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS;
if (this.componentWillReceiveProps) {
this.componentWillReceiveProps(nextProps, transaction);
}
}
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_STATE;
var nextState = this._pendingState || this.state;
this._pendingState = null;
if (this._pendingForceUpdate ||
!this.shouldComponentUpdate ||
this.shouldComponentUpdate(nextProps, nextState)) {
this._pendingForceUpdate = false;
// Will set `this.props` and `this.state`.
this._performComponentUpdate(nextProps, nextState, transaction);
} else {
// If it's determined that a component should not update, we still want
// to set props and state.
this.props = nextProps;
this.state = nextState;
}
this._compositeLifeCycleState = null;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {object} nextProps Next object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_performComponentUpdate: function(nextProps, nextState, transaction) {
var prevProps = this.props;
var prevState = this.state;
if (this.componentWillUpdate) {
this.componentWillUpdate(nextProps, nextState, transaction);
}
this.props = nextProps;
this.state = nextState;
this.updateComponent(transaction, prevProps, prevState);
if (this.componentDidUpdate) {
transaction.getReactMountReady().enqueue(
this,
this.componentDidUpdate.bind(this, prevProps, prevState)
);
}
},
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {object} prevProps
* @param {?object} prevState
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactCompositeComponent',
'updateComponent',
function(transaction, prevProps, prevState) {
ReactComponent.Mixin.updateComponent.call(this, transaction, prevProps);
var currentComponent = this._renderedComponent;
var nextComponent = this._renderValidatedComponent();
if (currentComponent.constructor === nextComponent.constructor) {
currentComponent.receiveProps(nextComponent.props, transaction);
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var currentComponentID = currentComponent._rootNodeID;
currentComponent.unmountComponent();
this._renderedComponent = nextComponent;
var nextMarkup = nextComponent.mountComponent(
thisID,
transaction,
this._mountDepth + 1
);
ReactComponent.DOMIDOperations.dangerouslyReplaceNodeWithMarkupByID(
currentComponentID,
nextMarkup
);
}
}
),
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldUpdateComponent`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
forceUpdate: function(callback) {
var compositeLifeCycleState = this._compositeLifeCycleState;
invariant(
this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'forceUpdate(...): Can only force an update on mounted or mounting ' +
'components.'
);
invariant(
compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'forceUpdate(...): Cannot force an update while unmounting component ' +
'or during an existing state transition (such as within `render`).'
);
this._pendingForceUpdate = true;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* @private
*/
_renderValidatedComponent: function() {
var renderedComponent;
ReactCurrentOwner.current = this;
try {
renderedComponent = this.render();
} catch (error) {
// IE8 requires `catch` in order to use `finally`.
throw error;
} finally {
ReactCurrentOwner.current = null;
}
invariant(
ReactComponent.isValidComponent(renderedComponent),
'%s.render(): A valid ReactComponent must be returned.',
this.constructor.displayName || 'ReactCompositeComponent'
);
return renderedComponent;
},
/**
* @private
*/
_bindAutoBindMethods: function() {
for (var autoBindKey in this.__reactAutoBindMap) {
if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
continue;
}
var method = this.__reactAutoBindMap[autoBindKey];
this[autoBindKey] = this._bindAutoBindMethod(method);
}
},
/**
* Binds a method to the component.
*
* @param {function} method Method to be bound.
* @private
*/
_bindAutoBindMethod: function(method) {
var component = this;
var boundMethod = function() {
return method.apply(component, arguments);
};
if (true) {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis) {
// 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) {
console.warn(
'bind(): React component methods may only be bound to the ' +
'component instance. See ' + componentName
);
} else if (arguments.length === 1) {
console.warn(
'bind(): You are binding a component method to the component. ' +
'React does this for you automatically in a high-performance ' +
'way, so you can safely remove this call. See ' + componentName
);
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments =
Array.prototype.slice.call(arguments, 1);
return reboundMethod;
};
}
return boundMethod;
}
};
var ReactCompositeComponentBase = function() {};
mixInto(ReactCompositeComponentBase, ReactComponent.Mixin);
mixInto(ReactCompositeComponentBase, ReactOwner.Mixin);
mixInto(ReactCompositeComponentBase, ReactPropTransferer.Mixin);
mixInto(ReactCompositeComponentBase, ReactCompositeComponentMixin);
/**
* Module for creating composite components.
*
* @class ReactCompositeComponent
* @extends ReactComponent
* @extends ReactOwner
* @extends ReactPropTransferer
*/
var ReactCompositeComponent = {
LifeCycle: CompositeLifeCycle,
Base: ReactCompositeComponentBase,
/**
* Creates a composite component class given a class specification.
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function(spec) {
var Constructor = function() {};
Constructor.prototype = new ReactCompositeComponentBase();
Constructor.prototype.constructor = Constructor;
mixSpecIntoComponent(Constructor, spec);
invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
);
if (true) {
if (Constructor.prototype.componentShouldUpdate) {
console.warn(
(spec.displayName || 'A component') + ' has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.'
);
}
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactCompositeComponentInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
var ConvenienceConstructor = function(props, children) {
var instance = new Constructor();
instance.construct.apply(instance, arguments);
return instance;
};
ConvenienceConstructor.componentConstructor = Constructor;
ConvenienceConstructor.originalSpec = spec;
return ConvenienceConstructor;
},
/**
* Checks if a value is a valid component constructor.
*
* @param {*}
* @return {boolean}
* @public
*/
isValidClass: function(componentClass) {
return componentClass instanceof Function &&
'componentConstructor' in componentClass &&
componentClass.componentConstructor instanceof Function;
}
};
module.exports = ReactCompositeComponent;
},{"./ReactComponent":25,"./ReactCurrentOwner":29,"./ReactOwner":53,"./ReactPerf":54,"./ReactPropTransferer":55,"./ReactUpdates":60,"./invariant":95,"./keyMirror":101,"./merge":104,"./mixInto":107,"./objMap":110}],29:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactCurrentOwner
*/
"use strict";
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*
* The depth indicate how many composite components are above this render level.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
},{}],30:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOM
* @typechecks static-only
*/
"use strict";
var ReactDOMComponent = require("./ReactDOMComponent");
var mergeInto = require("./mergeInto");
var objMapKeyVal = require("./objMapKeyVal");
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @param {string} tag Tag name (e.g. `div`).
* @param {boolean} omitClose True if the close tag should be omitted.
* @private
*/
function createDOMComponentClass(tag, omitClose) {
var Constructor = function() {};
Constructor.prototype = new ReactDOMComponent(tag, omitClose);
Constructor.prototype.constructor = Constructor;
Constructor.displayName = tag;
var ConvenienceConstructor = function(props, children) {
var instance = new Constructor();
instance.construct.apply(instance, arguments);
return instance;
};
ConvenienceConstructor.componentConstructor = Constructor;
return ConvenienceConstructor;
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOM = objMapKeyVal({
a: false,
abbr: false,
address: false,
area: false,
article: false,
aside: false,
audio: false,
b: false,
base: false,
bdi: false,
bdo: false,
big: false,
blockquote: false,
body: false,
br: true,
button: false,
canvas: false,
caption: false,
cite: false,
code: false,
col: true,
colgroup: false,
data: false,
datalist: false,
dd: false,
del: false,
details: false,
dfn: false,
div: false,
dl: false,
dt: false,
em: false,
embed: true,
fieldset: false,
figcaption: false,
figure: false,
footer: false,
form: false, // NOTE: Injected, see `ReactDOMForm`.
h1: false,
h2: false,
h3: false,
h4: false,
h5: false,
h6: false,
head: false,
header: false,
hr: true,
html: false,
i: false,
iframe: false,
img: true,
input: true,
ins: false,
kbd: false,
keygen: true,
label: false,
legend: false,
li: false,
link: false,
main: false,
map: false,
mark: false,
menu: false,
menuitem: false, // NOTE: Close tag should be omitted, but causes problems.
meta: true,
meter: false,
nav: false,
noscript: false,
object: false,
ol: false,
optgroup: false,
option: false,
output: false,
p: false,
param: true,
pre: false,
progress: false,
q: false,
rp: false,
rt: false,
ruby: false,
s: false,
samp: false,
script: false,
section: false,
select: false,
small: false,
source: false,
span: false,
strong: false,
style: false,
sub: false,
summary: false,
sup: false,
table: false,
tbody: false,
td: false,
textarea: false, // NOTE: Injected, see `ReactDOMTextarea`.
tfoot: false,
th: false,
thead: false,
time: false,
title: false,
tr: false,
track: true,
u: false,
ul: false,
'var': false,
video: false,
wbr: false,
// SVG
circle: false,
g: false,
line: false,
path: false,
polyline: false,
rect: false,
svg: false,
text: false
}, createDOMComponentClass);
var injection = {
injectComponentClasses: function(componentClasses) {
mergeInto(ReactDOM, componentClasses);
}
};
ReactDOM.injection = injection;
module.exports = ReactDOM;
},{"./ReactDOMComponent":32,"./mergeInto":106,"./objMapKeyVal":111}],31:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMButton
*/
"use strict";
var ReactCompositeComponent = require("./ReactCompositeComponent");
var ReactDOM = require("./ReactDOM");
var keyMirror = require("./keyMirror");
// Store a reference to the <button> `ReactDOMComponent`.
var button = ReactDOM.button;
var mouseListenerNames = keyMirror({
onClick: true,
onDoubleClick: true,
onMouseDown: true,
onMouseMove: true,
onMouseUp: true,
onClickCapture: true,
onDoubleClickCapture: true,
onMouseDownCapture: true,
onMouseMoveCapture: true,
onMouseUpCapture: true
});
/**
* Implements a <button> native component that does not receive mouse events
* when `disabled` is set.
*/
var ReactDOMButton = ReactCompositeComponent.createClass({
render: function() {
var props = {};
// Copy the props; except the mouse listeners if we're disabled
for (var key in this.props) {
if (this.props.hasOwnProperty(key) &&
(!this.props.disabled || !mouseListenerNames[key])) {
props[key] = this.props[key];
}
}
return button(props, this.props.children);
}
});
module.exports = ReactDOMButton;
},{"./ReactCompositeComponent":28,"./ReactDOM":30,"./keyMirror":101}],32:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMComponent
* @typechecks static-only
*/
"use strict";
var CSSPropertyOperations = require("./CSSPropertyOperations");
var DOMProperty = require("./DOMProperty");
var DOMPropertyOperations = require("./DOMPropertyOperations");
var ReactComponent = require("./ReactComponent");
var ReactEventEmitter = require("./ReactEventEmitter");
var ReactMultiChild = require("./ReactMultiChild");
var ReactMount = require("./ReactMount");
var ReactPerf = require("./ReactPerf");
var escapeTextForBrowser = require("./escapeTextForBrowser");
var invariant = require("./invariant");
var keyOf = require("./keyOf");
var merge = require("./merge");
var mixInto = require("./mixInto");
var putListener = ReactEventEmitter.putListener;
var deleteListener = ReactEventEmitter.deleteListener;
var registrationNames = ReactEventEmitter.registrationNames;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = {'string': true, 'number': true};
var STYLE = keyOf({style: null});
/**
* @param {?object} props
*/
function assertValidProps(props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
invariant(
props.children == null || props.dangerouslySetInnerHTML == null,
'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'
);
invariant(
props.style == null || typeof props.style === 'object',
'The `style` prop expects a mapping from style properties to values, ' +
'not a string.'
);
}
/**
* @constructor ReactDOMComponent
* @extends ReactComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(tag, omitClose) {
this._tagOpen = '<' + tag;
this._tagClose = omitClose ? '' : '</' + tag + '>';
this.tagName = tag.toUpperCase();
}
ReactDOMComponent.Mixin = {
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {string} rootID The root DOM ID for this node.
* @param {ReactReconcileTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {string} The computed markup.
*/
mountComponent: ReactPerf.measure(
'ReactDOMComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
assertValidProps(this.props);
return (
this._createOpenTagMarkup() +
this._createContentMarkup(transaction) +
this._tagClose
);
}
),
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see http://jsperf.com/obj-vs-arr-iteration
*
* @private
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkup: function() {
var props = this.props;
var ret = this._tagOpen;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNames[propKey]) {
putListener(this._rootNodeID, propKey, propValue);
} else {
if (propKey === STYLE) {
if (propValue) {
propValue = props.style = merge(props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue);
}
var markup =
DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
if (markup) {
ret += ' ' + markup;
}
}
}
var escapedID = escapeTextForBrowser(this._rootNodeID);
return ret + ' ' + ReactMount.ATTR_NAME + '="' + escapedID + '">';
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction} transaction
* @return {string} Content markup.
*/
_createContentMarkup: function(transaction) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = this.props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return innerHTML.__html;
}
} else {
var contentToUse =
CONTENT_TYPES[typeof this.props.children] ? this.props.children : null;
var childrenToUse = contentToUse != null ? null : this.props.children;
if (contentToUse != null) {
return escapeTextForBrowser(contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(
childrenToUse,
transaction
);
return mountImages.join('');
}
}
return '';
},
receiveProps: function(nextProps, transaction) {
assertValidProps(nextProps);
ReactComponent.Mixin.receiveProps.call(this, nextProps, transaction);
},
/**
* Updates a native DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @param {ReactReconcileTransaction} transaction
* @param {object} prevProps
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactDOMComponent',
'updateComponent',
function(transaction, prevProps) {
ReactComponent.Mixin.updateComponent.call(this, transaction, prevProps);
this._updateDOMProperties(prevProps);
this._updateDOMChildren(prevProps, transaction);
}
),
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} lastProps
*/
_updateDOMProperties: function(lastProps) {
var nextProps = this.props;
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) ||
!lastProps.hasOwnProperty(propKey)) {
continue;
}
if (propKey === STYLE) {
var lastStyle = lastProps[propKey];
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
} else if (registrationNames[propKey]) {
deleteListener(this._rootNodeID, propKey);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
ReactComponent.DOMIDOperations.deletePropertyByID(
this._rootNodeID,
propKey
);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = lastProps[propKey];
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
nextProp = nextProps.style = merge(nextProp);
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) &&
!nextProp.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
// Update styles that changed since `lastProp`.
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) &&
lastProp[styleName] !== nextProp[styleName]) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
// Relies on `updateStylesByID` not mutating `styleUpdates`.
styleUpdates = nextProp;
}
} else if (registrationNames[propKey]) {
putListener(this._rootNodeID, propKey, nextProp);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
ReactComponent.DOMIDOperations.updatePropertyByID(
this._rootNodeID,
propKey,
nextProp
);
}
}
if (styleUpdates) {
ReactComponent.DOMIDOperations.updateStylesByID(
this._rootNodeID,
styleUpdates
);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {ReactReconcileTransaction} transaction
*/
_updateDOMChildren: function(lastProps, transaction) {
var nextProps = this.props;
var lastContent =
CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
var nextContent =
CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
var lastHtml =
lastProps.dangerouslySetInnerHTML &&
lastProps.dangerouslySetInnerHTML.__html;
var nextHtml =
nextProps.dangerouslySetInnerHTML &&
nextProps.dangerouslySetInnerHTML.__html;
// Note the use of `!=` which checks for null or undefined.
var lastChildren = lastContent != null ? null : lastProps.children;
var nextChildren = nextContent != null ? null : nextProps.children;
// If we're switching from children to content/html or vice versa, remove
// the old content
var lastHasContentOrHtml = lastContent != null || lastHtml != null;
var nextHasContentOrHtml = nextContent != null || nextHtml != null;
if (lastChildren != null && nextChildren == null) {
this.updateChildren(null, transaction);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
ReactComponent.DOMIDOperations.updateInnerHTMLByID(
this._rootNodeID,
nextHtml
);
}
} else if (nextChildren != null) {
this.updateChildren(nextChildren, transaction);
}
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function() {
ReactEventEmitter.deleteAllListeners(this._rootNodeID);
ReactComponent.Mixin.unmountComponent.call(this);
this.unmountChildren();
}
};
mixInto(ReactDOMComponent, ReactComponent.Mixin);
mixInto(ReactDOMComponent, ReactDOMComponent.Mixin);
mixInto(ReactDOMComponent, ReactMultiChild.Mixin);
module.exports = ReactDOMComponent;
},{"./CSSPropertyOperations":3,"./DOMProperty":8,"./DOMPropertyOperations":9,"./ReactComponent":25,"./ReactEventEmitter":43,"./ReactMount":49,"./ReactMultiChild":51,"./ReactPerf":54,"./escapeTextForBrowser":82,"./invariant":95,"./keyOf":102,"./merge":104,"./mixInto":107}],33:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMForm
*/
"use strict";
var ReactCompositeComponent = require("./ReactCompositeComponent");
var ReactDOM = require("./ReactDOM");
var ReactEventEmitter = require("./ReactEventEmitter");
var EventConstants = require("./EventConstants");
// Store a reference to the <form> `ReactDOMComponent`.
var form = ReactDOM.form;
/**
* Since onSubmit doesn't bubble OR capture on the top level in IE8, we need
* to capture it on the <form> element itself. There are lots of hacks we could
* do to accomplish this, but the most reliable is to make <form> a
* composite component and use `componentDidMount` to attach the event handlers.
*/
var ReactDOMForm = ReactCompositeComponent.createClass({
render: function() {
// TODO: Instead of using `ReactDOM` directly, we should use JSX. However,
// `jshint` fails to parse JSX so in order for linting to work in the open
// source repo, we need to just use `ReactDOM.form`.
return this.transferPropsTo(form(null, this.props.children));
},
componentDidMount: function(node) {
ReactEventEmitter.trapBubbledEvent(
EventConstants.topLevelTypes.topSubmit,
'submit',
node
);
}
});
module.exports = ReactDOMForm;
},{"./EventConstants":14,"./ReactCompositeComponent":28,"./ReactDOM":30,"./ReactEventEmitter":43}],34:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMIDOperations
* @typechecks static-only
*/
/*jslint evil: true */
"use strict";
var CSSPropertyOperations = require("./CSSPropertyOperations");
var DOMChildrenOperations = require("./DOMChildrenOperations");
var DOMPropertyOperations = require("./DOMPropertyOperations");
var ReactMount = require("./ReactMount");
var getTextContentAccessor = require("./getTextContentAccessor");
var invariant = require("./invariant");
/**
* Errors for properties that should not be updated with `updatePropertyById()`.
*
* @type {object}
* @private
*/
var INVALID_PROPERTY_ERRORS = {
dangerouslySetInnerHTML:
'`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
style: '`style` must be set using `updateStylesByID()`.'
};
/**
* The DOM property to use when setting text content.
*
* @type {string}
* @private
*/
var textContentAccessor = getTextContentAccessor() || 'NA';
var LEADING_SPACE = /^ /;
/**
* Operations used to process updates to DOM nodes. This is made injectable via
* `ReactComponent.DOMIDOperations`.
*/
var ReactDOMIDOperations = {
/**
* Updates a DOM node with new property values. This should only be used to
* update DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A valid property name, see `DOMProperty`.
* @param {*} value New value of the property.
* @internal
*/
updatePropertyByID: function(id, name, value) {
var node = ReactMount.getNode(id);
invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
);
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (value != null) {
DOMPropertyOperations.setValueForProperty(node, name, value);
} else {
DOMPropertyOperations.deleteValueForProperty(node, name);
}
},
/**
* Updates a DOM node to remove a property. This should only be used to remove
* DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A property name to remove, see `DOMProperty`.
* @internal
*/
deletePropertyByID: function(id, name, value) {
var node = ReactMount.getNode(id);
invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
);
DOMPropertyOperations.deleteValueForProperty(node, name, value);
},
/**
* This should almost never be used instead of `updatePropertyByID()` due to
* the extra object allocation required by the API. That said, this is useful
* for batching up several operations across worker thread boundaries.
*
* @param {string} id ID of the node to update.
* @param {object} properties A mapping of valid property names.
* @internal
* @see {ReactDOMIDOperations.updatePropertyByID}
*/
updatePropertiesByID: function(id, properties) {
for (var name in properties) {
if (!properties.hasOwnProperty(name)) {
continue;
}
ReactDOMIDOperations.updatePropertiesByID(id, name, properties[name]);
}
},
/**
* Updates a DOM node with new style values. If a value is specified as '',
* the corresponding style property will be unset.
*
* @param {string} id ID of the node to update.
* @param {object} styles Mapping from styles to values.
* @internal
*/
updateStylesByID: function(id, styles) {
var node = ReactMount.getNode(id);
CSSPropertyOperations.setValueForStyles(node, styles);
},
/**
* Updates a DOM node's innerHTML.
*
* @param {string} id ID of the node to update.
* @param {string} html An HTML string.
* @internal
*/
updateInnerHTMLByID: function(id, html) {
var node = ReactMount.getNode(id);
// HACK: IE8- normalize whitespace in innerHTML, removing leading spaces.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
node.innerHTML = html.replace(LEADING_SPACE, ' ');
},
/**
* Updates a DOM node's text content set by `props.content`.
*
* @param {string} id ID of the node to update.
* @param {string} content Text content.
* @internal
*/
updateTextContentByID: function(id, content) {
var node = ReactMount.getNode(id);
node[textContentAccessor] = content;
},
/**
* Replaces a DOM node that exists in the document with markup.
*
* @param {string} id ID of child to be replaced.
* @param {string} markup Dangerous markup to inject in place of child.
* @internal
* @see {Danger.dangerouslyReplaceNodeWithMarkup}
*/
dangerouslyReplaceNodeWithMarkupByID: function(id, markup) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
},
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markup List of markup strings.
* @internal
*/
dangerouslyProcessChildrenUpdates: function(updates, markup) {
for (var i = 0; i < updates.length; i++) {
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
}
DOMChildrenOperations.processUpdates(updates, markup);
}
};
module.exports = ReactDOMIDOperations;
},{"./CSSPropertyOperations":3,"./DOMChildrenOperations":7,"./DOMPropertyOperations":9,"./ReactMount":49,"./getTextContentAccessor":93,"./invariant":95}],35:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMInput
*/
"use strict";
var DOMPropertyOperations = require("./DOMPropertyOperations");
var LinkedValueMixin = require("./LinkedValueMixin");
var ReactCompositeComponent = require("./ReactCompositeComponent");
var ReactDOM = require("./ReactDOM");
var ReactMount = require("./ReactMount");
var invariant = require("./invariant");
var merge = require("./merge");
// Store a reference to the <input> `ReactDOMComponent`.
var input = ReactDOM.input;
var instancesByReactID = {};
/**
* Implements an <input> native component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
*/
var ReactDOMInput = ReactCompositeComponent.createClass({
mixins: [LinkedValueMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
return {
checked: this.props.defaultChecked || false,
value: defaultValue != null ? defaultValue : ''
};
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
props.defaultChecked = null;
props.defaultValue = null;
props.checked =
this.props.checked != null ? this.props.checked : this.state.checked;
var value = this.getValue();
props.value = value != null ? value : this.state.value;
props.onChange = this._handleChange;
return input(props, this.props.children);
},
componentDidMount: function(rootNode) {
var id = ReactMount.getID(rootNode);
instancesByReactID[id] = this;
},
componentWillUnmount: function() {
var rootNode = this.getDOMNode();
var id = ReactMount.getID(rootNode);
delete instancesByReactID[id];
},
componentDidUpdate: function(prevProps, prevState, rootNode) {
if (this.props.checked != null) {
DOMPropertyOperations.setValueForProperty(
rootNode,
'checked',
this.props.checked || false
);
}
var value = this.getValue();
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = this.getOnChange();
if (onChange) {
this._isChanging = true;
returnValue = onChange(event);
this._isChanging = false;
}
this.setState({
checked: event.target.checked,
value: event.target.value
});
var name = this.props.name;
if (this.props.type === 'radio' && name != null) {
var rootNode = this.getDOMNode();
// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form, let's just use the global
// `getElementsByName` to ensure we don't miss anything.
var group = document.getElementsByName(name);
for (var i = 0, groupLen = group.length; i < groupLen; i++) {
var otherNode = group[i];
if (otherNode === rootNode ||
otherNode.nodeName !== 'INPUT' || otherNode.type !== 'radio' ||
otherNode.form !== rootNode.form) {
continue;
}
var otherID = ReactMount.getID(otherNode);
invariant(
otherID,
'ReactDOMInput: Mixing React and non-React radio inputs with the ' +
'same `name` is not supported.'
);
var otherInstance = instancesByReactID[otherID];
invariant(
otherInstance,
'ReactDOMInput: Unknown radio button ID %s.',
otherID
);
// In some cases, this will actually change the `checked` state value.
// In other cases, there's no change but this forces a reconcile upon
// which componentDidUpdate will reset the DOM property to whatever it
// should be.
otherInstance.setState({
checked: false
});
}
}
return returnValue;
}
});
module.exports = ReactDOMInput;
},{"./DOMPropertyOperations":9,"./LinkedValueMixin":21,"./ReactCompositeComponent":28,"./ReactDOM":30,"./ReactMount":49,"./invariant":95,"./merge":104}],36:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMOption
*/
"use strict";
var ReactCompositeComponent = require("./ReactCompositeComponent");
var ReactDOM = require("./ReactDOM");
// Store a reference to the <option> `ReactDOMComponent`.
var option = ReactDOM.option;
/**
* Implements an <option> native component that warns when `selected` is set.
*/
var ReactDOMOption = ReactCompositeComponent.createClass({
componentWillMount: function() {
// TODO (yungsters): Remove support for `selected` in <option>.
if (this.props.selected != null) {
if (true) {
console.warn(
'Use the `defaultValue` or `value` props on <select> instead of ' +
'setting `selected` on <option>.'
);
}
}
},
render: function() {
return option(this.props, this.props.children);
}
});
module.exports = ReactDOMOption;
},{"./ReactCompositeComponent":28,"./ReactDOM":30}],37:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMSelect
*/
"use strict";
var LinkedValueMixin = require("./LinkedValueMixin");
var ReactCompositeComponent = require("./ReactCompositeComponent");
var ReactDOM = require("./ReactDOM");
var invariant = require("./invariant");
var merge = require("./merge");
// Store a reference to the <select> `ReactDOMComponent`.
var select = ReactDOM.select;
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function selectValueType(props, propName, componentName) {
if (props[propName] == null) {
return;
}
if (props.multiple) {
invariant(
Array.isArray(props[propName]),
'The `%s` prop supplied to <select> must be an array if `multiple` is ' +
'true.',
propName
);
} else {
invariant(
!Array.isArray(props[propName]),
'The `%s` prop supplied to <select> must be a scalar value if ' +
'`multiple` is false.',
propName
);
}
}
/**
* If `value` is supplied, updates <option> elements on mount and update.
* @private
*/
function updateOptions() {
/*jshint validthis:true */
var propValue = this.getValue();
var value = propValue != null ? propValue : this.state.value;
var options = this.getDOMNode().options;
var selectedValue = '' + value;
for (var i = 0, l = options.length; i < l; i++) {
var selected = this.props.multiple ?
selectedValue.indexOf(options[i].value) >= 0 :
selected = options[i].value === selectedValue;
if (selected !== options[i].selected) {
options[i].selected = selected;
}
}
}
/**
* Implements a <select> native component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* string. If `multiple` is true, the prop must be an array of strings.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/
var ReactDOMSelect = ReactCompositeComponent.createClass({
mixins: [LinkedValueMixin],
propTypes: {
defaultValue: selectValueType,
value: selectValueType
},
getInitialState: function() {
return {value: this.props.defaultValue || (this.props.multiple ? [] : '')};
},
componentWillReceiveProps: function(nextProps) {
if (!this.props.multiple && nextProps.multiple) {
this.setState({value: [this.state.value]});
} else if (this.props.multiple && !nextProps.multiple) {
this.setState({value: this.state.value[0]});
}
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
props.onChange = this._handleChange;
props.value = null;
return select(props, this.props.children);
},
componentDidMount: updateOptions,
componentDidUpdate: updateOptions,
_handleChange: function(event) {
var returnValue;
var onChange = this.getOnChange();
if (onChange) {
this._isChanging = true;
returnValue = onChange(event);
this._isChanging = false;
}
var selectedValue;
if (this.props.multiple) {
selectedValue = [];
var options = event.target.options;
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
selectedValue.push(options[i].value);
}
}
} else {
selectedValue = event.target.value;
}
this.setState({value: selectedValue});
return returnValue;
}
});
module.exports = ReactDOMSelect;
},{"./LinkedValueMixin":21,"./ReactCompositeComponent":28,"./ReactDOM":30,"./invariant":95,"./merge":104}],38:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMSelection
*/
"use strict";
var getNodeForCharacterOffset = require("./getNodeForCharacterOffset");
var getTextContentAccessor = require("./getTextContentAccessor");
/**
* Get the appropriate anchor and focus node/offset pairs for IE.
*
* The catch here is that IE's selection API doesn't provide information
* about whether the selection is forward or backward, so we have to
* behave as though it's always forward.
*
* IE text differs from modern selection in that it behaves as though
* block elements end with a new line. This means character offsets will
* differ between the two APIs.
*
* @param {DOMElement} node
* @return {object}
*/
function getIEOffsets(node) {
var selection = document.selection;
var selectedRange = selection.createRange();
var selectedLength = selectedRange.text.length;
// Duplicate selection so we can move range without breaking user selection.
var fromStart = selectedRange.duplicate();
fromStart.moveToElementText(node);
fromStart.setEndPoint('EndToStart', selectedRange);
var startOffset = fromStart.text.length;
var endOffset = startOffset + selectedLength;
return {
start: startOffset,
end: endOffset
};
}
/**
* @param {DOMElement} node
* @return {?object}
*/
function getModernOffsets(node) {
var selection = window.getSelection();
if (selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode;
var anchorOffset = selection.anchorOffset;
var focusNode = selection.focusNode;
var focusOffset = selection.focusOffset;
var currentRange = selection.getRangeAt(0);
var rangeLength = currentRange.toString().length;
var tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node);
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var start = tempRange.toString().length;
var end = start + rangeLength;
// Detect whether the selection is backward.
var detectionRange = document.createRange();
detectionRange.setStart(anchorNode, anchorOffset);
detectionRange.setEnd(focusNode, focusOffset);
var isBackward = detectionRange.collapsed;
detectionRange.detach();
return {
start: isBackward ? end : start,
end: isBackward ? start : end
};
}
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setIEOffsets(node, offsets) {
var range = document.selection.createRange().duplicate();
var start, end;
if (typeof offsets.end === 'undefined') {
start = offsets.start;
end = start;
} else if (offsets.start > offsets.end) {
start = offsets.end;
end = offsets.start;
} else {
start = offsets.start;
end = offsets.end;
}
range.moveToElementText(node);
range.moveStart('character', start);
range.setEndPoint('EndToStart', range);
range.moveEnd('character', end - start);
range.select();
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setModernOffsets(node, offsets) {
var selection = window.getSelection();
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = typeof offsets.end === 'undefined' ?
start : Math.min(offsets.end, length);
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
range.detach();
}
}
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: function(node) {
var getOffsets = document.selection ? getIEOffsets : getModernOffsets;
return getOffsets(node);
},
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: function(node, offsets) {
var setOffsets = document.selection ? setIEOffsets : setModernOffsets;
setOffsets(node, offsets);
}
};
module.exports = ReactDOMSelection;
},{"./getNodeForCharacterOffset":91,"./getTextContentAccessor":93}],39:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMTextarea
*/
"use strict";
var DOMPropertyOperations = require("./DOMPropertyOperations");
var LinkedValueMixin = require("./LinkedValueMixin");
var ReactCompositeComponent = require("./ReactCompositeComponent");
var ReactDOM = require("./ReactDOM");
var invariant = require("./invariant");
var merge = require("./merge");
// Store a reference to the <textarea> `ReactDOMComponent`.
var textarea = ReactDOM.textarea;
/**
* Implements a <textarea> native component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/
var ReactDOMTextarea = ReactCompositeComponent.createClass({
mixins: [LinkedValueMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = this.props.children;
if (children != null) {
if (true) {
console.warn(
'Use the `defaultValue` or `value` props instead of setting ' +
'children on <textarea>.'
);
}
invariant(
defaultValue == null,
'If you supply `defaultValue` on a <textarea>, do not pass children.'
);
if (Array.isArray(children)) {
invariant(
children.length <= 1,
'<textarea> can only have at most one child.'
);
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
var value = this.getValue();
return {
// We save the initial value so that `ReactDOMComponent` doesn't update
// `textContent` (unnecessary since we update value).
// The initial value can be a boolean or object so that's why it's
// forced to be a string.
initialValue: '' + (value != null ? value : defaultValue),
value: defaultValue
};
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
var value = this.getValue();
invariant(
props.dangerouslySetInnerHTML == null,
'`dangerouslySetInnerHTML` does not make sense on <textarea>.'
);
props.defaultValue = null;
props.value = value != null ? value : this.state.value;
props.onChange = this._handleChange;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.
return textarea(props, this.state.initialValue);
},
componentDidUpdate: function(prevProps, prevState, rootNode) {
var value = this.getValue();
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = this.getOnChange();
if (onChange) {
this._isChanging = true;
returnValue = onChange(event);
this._isChanging = false;
}
this.setState({value: event.target.value});
return returnValue;
}
});
module.exports = ReactDOMTextarea;
},{"./DOMPropertyOperations":9,"./LinkedValueMixin":21,"./ReactCompositeComponent":28,"./ReactDOM":30,"./invariant":95,"./merge":104}],40:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDefaultBatchingStrategy
*/
"use strict";
var ReactUpdates = require("./ReactUpdates");
var Transaction = require("./Transaction");
var emptyFunction = require("./emptyFunction");
var mixInto = require("./mixInto");
var RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function() {
ReactDefaultBatchingStrategy.isBatchingUpdates = false;
}
};
var FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
};
var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES];
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
mixInto(ReactDefaultBatchingStrategyTransaction, Transaction.Mixin);
mixInto(ReactDefaultBatchingStrategyTransaction, {
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
}
});
var transaction = new ReactDefaultBatchingStrategyTransaction();
var ReactDefaultBatchingStrategy = {
isBatchingUpdates: false,
/**
* Call the provided function in a context within which calls to `setState`
* and friends are batched such that components aren't updated unnecessarily.
*/
batchedUpdates: function(callback, param) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(param);
} else {
transaction.perform(callback, null, param);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
},{"./ReactUpdates":60,"./Transaction":72,"./emptyFunction":81,"./mixInto":107}],41:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDefaultInjection
*/
"use strict";
var ReactDOM = require("./ReactDOM");
var ReactDOMButton = require("./ReactDOMButton");
var ReactDOMForm = require("./ReactDOMForm");
var ReactDOMInput = require("./ReactDOMInput");
var ReactDOMOption = require("./ReactDOMOption");
var ReactDOMSelect = require("./ReactDOMSelect");
var ReactDOMTextarea = require("./ReactDOMTextarea");
var ReactEventEmitter = require("./ReactEventEmitter");
var ReactEventTopLevelCallback = require("./ReactEventTopLevelCallback");
var ReactPerf = require("./ReactPerf");
var DefaultDOMPropertyConfig = require("./DefaultDOMPropertyConfig");
var DOMProperty = require("./DOMProperty");
var ChangeEventPlugin = require("./ChangeEventPlugin");
var CompositionEventPlugin = require("./CompositionEventPlugin");
var DefaultEventPluginOrder = require("./DefaultEventPluginOrder");
var EnterLeaveEventPlugin = require("./EnterLeaveEventPlugin");
var EventPluginHub = require("./EventPluginHub");
var MobileSafariClickEventPlugin = require("./MobileSafariClickEventPlugin");
var ReactInstanceHandles = require("./ReactInstanceHandles");
var SelectEventPlugin = require("./SelectEventPlugin");
var SimpleEventPlugin = require("./SimpleEventPlugin");
var ReactDefaultBatchingStrategy = require("./ReactDefaultBatchingStrategy");
var ReactUpdates = require("./ReactUpdates");
function inject() {
ReactEventEmitter.TopLevelCallbackCreator = ReactEventTopLevelCallback;
/**
* Inject module for resolving DOM hierarchy and plugin ordering.
*/
EventPluginHub.injection.injectEventPluginOrder(DefaultEventPluginOrder);
EventPluginHub.injection.injectInstanceHandle(ReactInstanceHandles);
/**
* Some important event plugins included by default (without having to require
* them).
*/
EventPluginHub.injection.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
CompositionEventPlugin: CompositionEventPlugin,
MobileSafariClickEventPlugin: MobileSafariClickEventPlugin,
SelectEventPlugin: SelectEventPlugin
});
ReactDOM.injection.injectComponentClasses({
button: ReactDOMButton,
form: ReactDOMForm,
input: ReactDOMInput,
option: ReactDOMOption,
select: ReactDOMSelect,
textarea: ReactDOMTextarea
});
DOMProperty.injection.injectDOMPropertyConfig(DefaultDOMPropertyConfig);
if (true) {
ReactPerf.injection.injectMeasure(require("./ReactDefaultPerf").measure);
}
ReactUpdates.injection.injectBatchingStrategy(
ReactDefaultBatchingStrategy
);
}
module.exports = {
inject: inject
};
},{"./ChangeEventPlugin":5,"./CompositionEventPlugin":6,"./DOMProperty":8,"./DefaultDOMPropertyConfig":11,"./DefaultEventPluginOrder":12,"./EnterLeaveEventPlugin":13,"./EventPluginHub":16,"./MobileSafariClickEventPlugin":22,"./ReactDOM":30,"./ReactDOMButton":31,"./ReactDOMForm":33,"./ReactDOMInput":35,"./ReactDOMOption":36,"./ReactDOMSelect":37,"./ReactDOMTextarea":39,"./ReactDefaultBatchingStrategy":40,"./ReactDefaultPerf":42,"./ReactEventEmitter":43,"./ReactEventTopLevelCallback":45,"./ReactInstanceHandles":47,"./ReactPerf":54,"./ReactUpdates":60,"./SelectEventPlugin":61,"./SimpleEventPlugin":62}],42:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDefaultPerf
* @typechecks static-only
*/
"use strict";
var performanceNow = require("./performanceNow");
var ReactDefaultPerf = {};
if (true) {
ReactDefaultPerf = {
/**
* Gets the stored information for a given object's function.
*
* @param {string} objName
* @param {string} fnName
* @return {?object}
*/
getInfo: function(objName, fnName) {
if (!this.info[objName] || !this.info[objName][fnName]) {
return null;
}
return this.info[objName][fnName];
},
/**
* Gets the logs pertaining to a given object's function.
*
* @param {string} objName
* @param {string} fnName
* @return {?array<object>}
*/
getLogs: function(objName, fnName) {
if (!this.getInfo(objName, fnName)) {
return null;
}
return this.logs.filter(function(log) {
return log.objName === objName && log.fnName === fnName;
});
},
/**
* Runs through the logs and builds an array of arrays, where each array
* walks through the mounting/updating of each component underneath.
*
* @param {string} rootID The reactID of the root node, e.g. '.r[2cpyq]'
* @return {array<array>}
*/
getRawRenderHistory: function(rootID) {
var history = [];
/**
* Since logs are added after the method returns, the logs are in a sense
* upside-down: the inner-most elements from mounting/updating are logged
* first, and the last addition to the log is the top renderComponent.
* Therefore, we flip the logs upside down for ease of processing, and
* reverse the history array at the end so the earliest event has index 0.
*/
var logs = this.logs.filter(function(log) {
return log.reactID.indexOf(rootID) === 0;
}).reverse();
var subHistory = [];
logs.forEach(function(log, i) {
if (i && log.reactID === rootID && logs[i - 1].reactID !== rootID) {
subHistory.length && history.push(subHistory);
subHistory = [];
}
subHistory.push(log);
});
if (subHistory.length) {
history.push(subHistory);
}
return history.reverse();
},
/**
* Runs through the logs and builds an array of strings, where each string
* is a multiline formatted way of walking through the mounting/updating
* underneath.
*
* @param {string} rootID The reactID of the root node, e.g. '.r[2cpyq]'
* @return {array<string>}
*/
getRenderHistory: function(rootID) {
var history = this.getRawRenderHistory(rootID);
return history.map(function(subHistory) {
var headerString = (
'log# Component (execution time) [bloat from logging]\n' +
'================================================================\n'
);
return headerString + subHistory.map(function(log) {
// Add two spaces for every layer in the reactID.
var indents = '\t' + Array(log.reactID.split('.[').length).join(' ');
var delta = _microTime(log.timing.delta);
var bloat = _microTime(log.timing.timeToLog);
return log.index + indents + log.name + ' (' + delta + 'ms)' +
' [' + bloat + 'ms]';
}).join('\n');
});
},
/**
* Print the render history from `getRenderHistory` using console.log.
* This is currently the best way to display perf data from
* any React component; working on that.
*
* @param {string} rootID The reactID of the root node, e.g. '.r[2cpyq]'
* @param {number} index
*/
printRenderHistory: function(rootID, index) {
var history = this.getRenderHistory(rootID);
if (!history[index]) {
console.warn(
'Index', index, 'isn\'t available! ' +
'The render history is', history.length, 'long.'
);
return;
}
console.log(
'Loading render history #' + (index + 1) +
' of ' + history.length + ':\n' + history[index]
);
},
/**
* Prints the heatmap legend to console, showing how the colors correspond
* with render times. This relies on console.log styles.
*/
printHeatmapLegend: function() {
if (!this.options.heatmap.enabled) {
return;
}
var max = this.info.React
&& this.info.React.renderComponent
&& this.info.React.renderComponent.max;
if (max) {
var logStr = 'Heatmap: ';
for (var ii = 0; ii <= 10 * max; ii += max) {
logStr += '%c ' + (Math.round(ii) / 10) + 'ms ';
}
console.log(
logStr,
'background-color: hsla(100, 100%, 50%, 0.6);',
'background-color: hsla( 90, 100%, 50%, 0.6);',
'background-color: hsla( 80, 100%, 50%, 0.6);',
'background-color: hsla( 70, 100%, 50%, 0.6);',
'background-color: hsla( 60, 100%, 50%, 0.6);',
'background-color: hsla( 50, 100%, 50%, 0.6);',
'background-color: hsla( 40, 100%, 50%, 0.6);',
'background-color: hsla( 30, 100%, 50%, 0.6);',
'background-color: hsla( 20, 100%, 50%, 0.6);',
'background-color: hsla( 10, 100%, 50%, 0.6);',
'background-color: hsla( 0, 100%, 50%, 0.6);'
);
}
},
/**
* Measure a given function with logging information, and calls a callback
* if there is one.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
measure: function(objName, fnName, func) {
var info = _getNewInfo(objName, fnName);
var fnArgs = _getFnArguments(func);
return function() {
var timeBeforeFn = performanceNow();
var fnReturn = func.apply(this, arguments);
var timeAfterFn = performanceNow();
/**
* Hold onto arguments in a readable way: args[1] -> args.component.
* args is also passed to the callback, so if you want to save an
* argument in the log, do so in the callback.
*/
var args = {};
for (var i = 0; i < arguments.length; i++) {
args[fnArgs[i]] = arguments[i];
}
var log = {
index: ReactDefaultPerf.logs.length,
fnName: fnName,
objName: objName,
timing: {
before: timeBeforeFn,
after: timeAfterFn,
delta: timeAfterFn - timeBeforeFn
}
};
ReactDefaultPerf.logs.push(log);
/**
* The callback gets:
* - this (the component)
* - the original method's arguments
* - what the method returned
* - the log object, and
* - the wrapped method's info object.
*/
var callback = _getCallback(objName, fnName);
callback && callback(this, args, fnReturn, log, info);
log.timing.timeToLog = performanceNow() - timeAfterFn;
return fnReturn;
};
},
/**
* Holds information on wrapped objects/methods.
* For instance, ReactDefaultPerf.info.React.renderComponent
*/
info: {},
/**
* Holds all of the logs. Filter this to pull desired information.
*/
logs: [],
/**
* Toggle settings for ReactDefaultPerf
*/
options: {
/**
* The heatmap sets the background color of the React containers
* according to how much total time has been spent rendering them.
* The most temporally expensive component is set as pure red,
* and the others are colored from green to red as a fraction
* of that max component time.
*/
heatmap: {
enabled: true
}
}
};
/**
* Gets a info area for a given object's function, adding a new one if
* necessary.
*
* @param {string} objName
* @param {string} fnName
* @return {object}
*/
var _getNewInfo = function(objName, fnName) {
var info = ReactDefaultPerf.getInfo(objName, fnName);
if (info) {
return info;
}
ReactDefaultPerf.info[objName] = ReactDefaultPerf.info[objName] || {};
return ReactDefaultPerf.info[objName][fnName] = {
getLogs: function() {
return ReactDefaultPerf.getLogs(objName, fnName);
}
};
};
/**
* Gets a list of the argument names from a function's definition.
* This is useful for storing arguments by their names within wrapFn().
*
* @param {function} fn
* @return {array<string>}
*/
var _getFnArguments = function(fn) {
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var fnStr = fn.toString().replace(STRIP_COMMENTS, '');
fnStr = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')'));
return fnStr.match(/([^\s,]+)/g);
};
/**
* Store common callbacks within ReactDefaultPerf.
*
* @param {string} objName
* @param {string} fnName
* @return {?function}
*/
var _getCallback = function(objName, fnName) {
switch (objName + '.' + fnName) {
case 'React.renderComponent':
return _renderComponentCallback;
case 'ReactDOMComponent.mountComponent':
case 'ReactDOMComponent.updateComponent':
return _nativeComponentCallback;
case 'ReactCompositeComponent.mountComponent':
case 'ReactCompositeComponent.updateComponent':
return _compositeComponentCallback;
default:
return null;
}
};
/**
* Callback function for React.renderComponent
*
* @param {object} component
* @param {object} args
* @param {?object} fnReturn
* @param {object} log
* @param {object} info
*/
var _renderComponentCallback =
function(component, args, fnReturn, log, info) {
log.name = args.nextComponent.constructor.displayName || '[unknown]';
log.reactID = fnReturn._rootNodeID || null;
if (ReactDefaultPerf.options.heatmap.enabled) {
var container = args.container;
if (!container.loggedByReactDefaultPerf) {
container.loggedByReactDefaultPerf = true;
info.components = info.components || [];
info.components.push(container);
}
container.count = container.count || 0;
container.count += log.timing.delta;
info.max = info.max || 0;
if (container.count > info.max) {
info.max = container.count;
info.components.forEach(function(component) {
_setHue(component, 100 - 100 * component.count / info.max);
});
} else {
_setHue(container, 100 - 100 * container.count / info.max);
}
}
};
/**
* Callback function for ReactDOMComponent
*
* @param {object} component
* @param {object} args
* @param {?object} fnReturn
* @param {object} log
* @param {object} info
*/
var _nativeComponentCallback =
function(component, args, fnReturn, log, info) {
log.name = component.tagName || '[unknown]';
log.reactID = component._rootNodeID;
};
/**
* Callback function for ReactCompositeComponent
*
* @param {object} component
* @param {object} args
* @param {?object} fnReturn
* @param {object} log
* @param {object} info
*/
var _compositeComponentCallback =
function(component, args, fnReturn, log, info) {
log.name = component.constructor.displayName || '[unknown]';
log.reactID = component._rootNodeID;
};
/**
* Using the hsl() background-color attribute, colors an element.
*
* @param {DOMElement} el
* @param {number} hue [0 for red, 120 for green, 240 for blue]
*/
var _setHue = function(el, hue) {
el.style.backgroundColor = 'hsla(' + hue + ', 100%, 50%, 0.6)';
};
/**
* Round to the thousandth place.
* @param {number} time
* @return {number}
*/
var _microTime = function(time) {
return Math.round(time * 1000) / 1000;
};
}
module.exports = ReactDefaultPerf;
},{"./performanceNow":112}],43:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactEventEmitter
* @typechecks static-only
*/
"use strict";
var EventConstants = require("./EventConstants");
var EventListener = require("./EventListener");
var EventPluginHub = require("./EventPluginHub");
var ExecutionEnvironment = require("./ExecutionEnvironment");
var ReactEventEmitterMixin = require("./ReactEventEmitterMixin");
var ViewportMetrics = require("./ViewportMetrics");
var invariant = require("./invariant");
var isEventSupported = require("./isEventSupported");
var merge = require("./merge");
/**
* Summary of `ReactEventEmitter` event handling:
*
* - Top-level delegation is used to trap native browser events. We normalize
* and de-duplicate events to account for browser quirks.
*
* - Forward these native events (with the associated top-level type used to
* trap it) to `EventPluginHub`, which in turn will ask plugins if they want
* to extract any synthetic events.
*
* - The `EventPluginHub` will then process each event by annotating them with
* "dispatches", a sequence of listeners and IDs that care about that event.
*
* - The `EventPluginHub` then dispatches the events.
*
* Overview of React and the event system:
*
* .
* +------------+ .
* | DOM | .
* +------------+ . +-----------+
* + . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +-----------.--->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | Emitter | . | |<---+|Plugin | |other plugin|
* | | . | | +-----------+ | utilities |
* | +-----------.---------+ | +------------+
* | | | . +----|---------+
* +-----|------+ . | ^ +-----------+
* | . | | |Enter/Leave|
* + . | +-------+|Plugin |
* +-------------+ . v +-----------+
* | application | . +----------+
* |-------------| . | callback |
* | | . | registry |
* | | . +----------+
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {DOMEventTarget} element Element on which to attach listener.
* @internal
*/
function trapBubbledEvent(topLevelType, handlerBaseName, element) {
EventListener.listen(
element,
handlerBaseName,
ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback(
topLevelType
)
);
}
/**
* Traps a top-level event by using event capturing.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {DOMEventTarget} element Element on which to attach listener.
* @internal
*/
function trapCapturedEvent(topLevelType, handlerBaseName, element) {
EventListener.capture(
element,
handlerBaseName,
ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback(
topLevelType
)
);
}
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
*
* NOTE: Scroll events do not bubble.
*
* @private
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
function registerScrollValueMonitoring() {
var refresh = ViewportMetrics.refreshScrollValues;
EventListener.listen(window, 'scroll', refresh);
EventListener.listen(window, 'resize', refresh);
}
/**
* `ReactEventEmitter` is used to attach top-level event listeners. For example:
*
* ReactEventEmitter.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*
* @internal
*/
var ReactEventEmitter = merge(ReactEventEmitterMixin, {
/**
* React references `ReactEventTopLevelCallback` using this property in order
* to allow dependency injection.
*/
TopLevelCallbackCreator: null,
/**
* Ensures that top-level event delegation listeners are installed.
*
* There are issues with listening to both touch events and mouse events on
* the top-level, so we make the caller choose which one to listen to. (If
* there's a touch top-level listeners, anchors don't receive clicks for some
* reason, and only in some cases).
*
* @param {boolean} touchNotMouse Listen to touch events instead of mouse.
* @param {DOMDocument} contentDocument DOM document to listen on
*/
ensureListening: function(touchNotMouse, contentDocument) {
invariant(
ExecutionEnvironment.canUseDOM,
'ensureListening(...): Cannot toggle event listening in a Worker ' +
'thread. This is likely a bug in the framework. Please report ' +
'immediately.'
);
invariant(
ReactEventEmitter.TopLevelCallbackCreator,
'ensureListening(...): Cannot be called without a top level callback ' +
'creator being injected.'
);
// Call out to base implementation.
ReactEventEmitterMixin.ensureListening.call(
ReactEventEmitter,
{
touchNotMouse: touchNotMouse,
contentDocument: contentDocument
}
);
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function(enabled) {
invariant(
ExecutionEnvironment.canUseDOM,
'setEnabled(...): Cannot toggle event listening in a Worker thread. ' +
'This is likely a bug in the framework. Please report immediately.'
);
if (ReactEventEmitter.TopLevelCallbackCreator) {
ReactEventEmitter.TopLevelCallbackCreator.setEnabled(enabled);
}
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function() {
return !!(
ReactEventEmitter.TopLevelCallbackCreator &&
ReactEventEmitter.TopLevelCallbackCreator.isEnabled()
);
},
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {boolean} touchNotMouse Listen to touch events instead of mouse.
* @param {DOMDocument} contentDocument Document which owns the container
* @private
* @see http://www.quirksmode.org/dom/events/keys.html.
*/
listenAtTopLevel: function(touchNotMouse, contentDocument) {
invariant(
!contentDocument._isListening,
'listenAtTopLevel(...): Cannot setup top-level listener more than once.'
);
var topLevelTypes = EventConstants.topLevelTypes;
var mountAt = contentDocument;
registerScrollValueMonitoring();
trapBubbledEvent(topLevelTypes.topMouseOver, 'mouseover', mountAt);
trapBubbledEvent(topLevelTypes.topMouseDown, 'mousedown', mountAt);
trapBubbledEvent(topLevelTypes.topMouseUp, 'mouseup', mountAt);
trapBubbledEvent(topLevelTypes.topMouseMove, 'mousemove', mountAt);
trapBubbledEvent(topLevelTypes.topMouseOut, 'mouseout', mountAt);
trapBubbledEvent(topLevelTypes.topClick, 'click', mountAt);
trapBubbledEvent(topLevelTypes.topDoubleClick, 'dblclick', mountAt);
if (touchNotMouse) {
trapBubbledEvent(topLevelTypes.topTouchStart, 'touchstart', mountAt);
trapBubbledEvent(topLevelTypes.topTouchEnd, 'touchend', mountAt);
trapBubbledEvent(topLevelTypes.topTouchMove, 'touchmove', mountAt);
trapBubbledEvent(topLevelTypes.topTouchCancel, 'touchcancel', mountAt);
}
trapBubbledEvent(topLevelTypes.topKeyUp, 'keyup', mountAt);
trapBubbledEvent(topLevelTypes.topKeyPress, 'keypress', mountAt);
trapBubbledEvent(topLevelTypes.topKeyDown, 'keydown', mountAt);
trapBubbledEvent(topLevelTypes.topInput, 'input', mountAt);
trapBubbledEvent(topLevelTypes.topChange, 'change', mountAt);
trapBubbledEvent(
topLevelTypes.topSelectionChange,
'selectionchange',
mountAt
);
trapBubbledEvent(
topLevelTypes.topCompositionEnd,
'compositionend',
mountAt
);
trapBubbledEvent(
topLevelTypes.topCompositionStart,
'compositionstart',
mountAt
);
trapBubbledEvent(
topLevelTypes.topCompositionUpdate,
'compositionupdate',
mountAt
);
if (isEventSupported('drag')) {
trapBubbledEvent(topLevelTypes.topDrag, 'drag', mountAt);
trapBubbledEvent(topLevelTypes.topDragEnd, 'dragend', mountAt);
trapBubbledEvent(topLevelTypes.topDragEnter, 'dragenter', mountAt);
trapBubbledEvent(topLevelTypes.topDragExit, 'dragexit', mountAt);
trapBubbledEvent(topLevelTypes.topDragLeave, 'dragleave', mountAt);
trapBubbledEvent(topLevelTypes.topDragOver, 'dragover', mountAt);
trapBubbledEvent(topLevelTypes.topDragStart, 'dragstart', mountAt);
trapBubbledEvent(topLevelTypes.topDrop, 'drop', mountAt);
}
if (isEventSupported('wheel')) {
trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt);
} else if (isEventSupported('mousewheel')) {
trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt);
} else {
// Firefox needs to capture a different mouse scroll event.
// @see http://www.quirksmode.org/dom/events/tests/scroll.html
trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt);
}
// IE<9 does not support capturing so just trap the bubbled event there.
if (isEventSupported('scroll', true)) {
trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt);
} else {
trapBubbledEvent(topLevelTypes.topScroll, 'scroll', window);
}
if (isEventSupported('focus', true)) {
trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt);
trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt);
} else if (isEventSupported('focusin')) {
// IE has `focusin` and `focusout` events which bubble.
// @see
// http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt);
trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt);
}
if (isEventSupported('copy')) {
trapBubbledEvent(topLevelTypes.topCopy, 'copy', mountAt);
trapBubbledEvent(topLevelTypes.topCut, 'cut', mountAt);
trapBubbledEvent(topLevelTypes.topPaste, 'paste', mountAt);
}
},
registrationNames: EventPluginHub.registrationNames,
putListener: EventPluginHub.putListener,
getListener: EventPluginHub.getListener,
deleteListener: EventPluginHub.deleteListener,
deleteAllListeners: EventPluginHub.deleteAllListeners,
trapBubbledEvent: trapBubbledEvent,
trapCapturedEvent: trapCapturedEvent
});
module.exports = ReactEventEmitter;
},{"./EventConstants":14,"./EventListener":15,"./EventPluginHub":16,"./ExecutionEnvironment":20,"./ReactEventEmitterMixin":44,"./ViewportMetrics":73,"./invariant":95,"./isEventSupported":96,"./merge":104}],44:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactEventEmitterMixin
*/
"use strict";
var EventPluginHub = require("./EventPluginHub");
var ReactUpdates = require("./ReactUpdates");
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events);
EventPluginHub.processEventQueue();
}
var ReactEventEmitterMixin = {
/**
* Whether or not `ensureListening` has been invoked.
* @type {boolean}
* @private
*/
_isListening: false,
/**
* Function, must be implemented. Listens to events on the top level of the
* application.
*
* @abstract
*
* listenAtTopLevel: null,
*/
/**
* Ensures that top-level event delegation listeners are installed.
*
* There are issues with listening to both touch events and mouse events on
* the top-level, so we make the caller choose which one to listen to. (If
* there's a touch top-level listeners, anchors don't receive clicks for some
* reason, and only in some cases).
*
* @param {*} config Configuration passed through to `listenAtTopLevel`.
*/
ensureListening: function(config) {
if (!config.contentDocument._reactIsListening) {
this.listenAtTopLevel(config.touchNotMouse, config.contentDocument);
config.contentDocument._reactIsListening = true;
}
},
/**
* Streams a fired top-level event to `EventPluginHub` where plugins have the
* opportunity to create `ReactEvent`s to be dispatched.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native environment event.
*/
handleTopLevel: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var events = EventPluginHub.extractEvents(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
);
// Event queue being processed in the same cycle allows `preventDefault`.
ReactUpdates.batchedUpdates(runEventQueueInBatch, events);
}
};
module.exports = ReactEventEmitterMixin;
},{"./EventPluginHub":16,"./ReactUpdates":60}],45:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactEventTopLevelCallback
* @typechecks static-only
*/
"use strict";
var ReactEventEmitter = require("./ReactEventEmitter");
var ReactMount = require("./ReactMount");
var getEventTarget = require("./getEventTarget");
/**
* @type {boolean}
* @private
*/
var _topLevelListenersEnabled = true;
/**
* Top-level callback creator used to implement event handling using delegation.
* This is used via dependency injection.
*/
var ReactEventTopLevelCallback = {
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function(enabled) {
_topLevelListenersEnabled = !!enabled;
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function() {
return _topLevelListenersEnabled;
},
/**
* Creates a callback for the supplied `topLevelType` that could be added as
* a listener to the document. The callback computes a `topLevelTarget` which
* should be the root node of a mounted React component where the listener
* is attached.
*
* @param {string} topLevelType Record from `EventConstants`.
* @return {function} Callback for handling top-level events.
*/
createTopLevelCallback: function(topLevelType) {
return function(nativeEvent) {
if (!_topLevelListenersEnabled) {
return;
}
// TODO: Remove when synthetic events are ready, this is for IE<9.
if (nativeEvent.srcElement &&
nativeEvent.srcElement !== nativeEvent.target) {
nativeEvent.target = nativeEvent.srcElement;
}
var topLevelTarget = ReactMount.getFirstReactDOM(
getEventTarget(nativeEvent)
) || window;
var topLevelTargetID = ReactMount.getID(topLevelTarget) || '';
ReactEventEmitter.handleTopLevel(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
);
};
}
};
module.exports = ReactEventTopLevelCallback;
},{"./ReactEventEmitter":43,"./ReactMount":49,"./getEventTarget":89}],46:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactInputSelection
*/
"use strict";
var ReactDOMSelection = require("./ReactDOMSelection");
var getActiveElement = require("./getActiveElement");
var nodeContains = require("./nodeContains");
function isInDocument(node) {
return nodeContains(document.documentElement, node);
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function(elem) {
return elem && (
(elem.nodeName === 'INPUT' && elem.type === 'text') ||
elem.nodeName === 'TEXTAREA' ||
elem.contentEditable === 'true'
);
},
getSelectionInformation: function() {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange:
ReactInputSelection.hasSelectionCapabilities(focusedElem) ?
ReactInputSelection.getSelection(focusedElem) :
null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function(priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem &&
isInDocument(priorFocusedElem)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(
priorFocusedElem,
priorSelectionRange
);
}
priorFocusedElem.focus();
}
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function(input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else if (document.selection && input.nodeName === 'INPUT') {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
if (range.parentElement() === input) {
selection = {
start: -range.moveStart('character', -input.value.length),
end: -range.moveEnd('character', -input.value.length)
};
}
} else {
// Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
}
return selection || {start: 0, end: 0};
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function(input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (typeof end === 'undefined') {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else if (document.selection && input.nodeName === 'INPUT') {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
ReactDOMSelection.setOffsets(input, offsets);
}
}
};
module.exports = ReactInputSelection;
},{"./ReactDOMSelection":38,"./getActiveElement":88,"./nodeContains":109}],47:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactInstanceHandles
* @typechecks static-only
*/
"use strict";
var invariant = require("./invariant");
var SEPARATOR = '.';
var SEPARATOR_LENGTH = SEPARATOR.length;
/**
* Maximum depth of traversals before we consider the possibility of a bad ID.
*/
var MAX_TREE_DEPTH = 100;
/**
* Size of the reactRoot ID space. We generate random numbers for React root
* IDs and if there's a collision the events and DOM update system will
* get confused. If we assume 100 React components per page, and a user
* loads 1 page per minute 24/7 for 50 years, with a mount point space of
* 9,999,999 the likelihood of never having a collision is 99.997%.
*/
var GLOBAL_MOUNT_POINT_MAX = 9999999;
/**
* Creates a DOM ID prefix to use when mounting React components.
*
* @param {number} index A unique integer
* @return {string} React root ID.
* @internal
*/
function getReactRootIDString(index) {
return SEPARATOR + 'r[' + index.toString(36) + ']';
}
/**
* Checks if a character in the supplied ID is a separator or the end.
*
* @param {string} id A React DOM ID.
* @param {number} index Index of the character to check.
* @return {boolean} True if the character is a separator or end of the ID.
* @private
*/
function isBoundary(id, index) {
return id.charAt(index) === SEPARATOR || index === id.length;
}
/**
* Checks if the supplied string is a valid React DOM ID.
*
* @param {string} id A React DOM ID, maybe.
* @return {boolean} True if the string is a valid React DOM ID.
* @private
*/
function isValidID(id) {
return id === '' || (
id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR
);
}
/**
* Checks if the first ID is an ancestor of or equal to the second ID.
*
* @param {string} ancestorID
* @param {string} descendantID
* @return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
* @internal
*/
function isAncestorIDOf(ancestorID, descendantID) {
return (
descendantID.indexOf(ancestorID) === 0 &&
isBoundary(descendantID, ancestorID.length)
);
}
/**
* Gets the parent ID of the supplied React DOM ID, `id`.
*
* @param {string} id ID of a component.
* @return {string} ID of the parent, or an empty string.
* @private
*/
function getParentID(id) {
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
}
/**
* Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
* supplied `destinationID`. If they are equal, the ID is returned.
*
* @param {string} ancestorID ID of an ancestor node of `destinationID`.
* @param {string} destinationID ID of the destination node.
* @return {string} Next ID on the path from `ancestorID` to `destinationID`.
* @private
*/
function getNextDescendantID(ancestorID, destinationID) {
invariant(
isValidID(ancestorID) && isValidID(destinationID),
'getNextDescendantID(%s, %s): Received an invalid React DOM ID.',
ancestorID,
destinationID
);
invariant(
isAncestorIDOf(ancestorID, destinationID),
'getNextDescendantID(...): React has made an invalid assumption about ' +
'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.',
ancestorID,
destinationID
);
if (ancestorID === destinationID) {
return ancestorID;
}
// Skip over the ancestor and the immediate separator. Traverse until we hit
// another separator or we reach the end of `destinationID`.
var start = ancestorID.length + SEPARATOR_LENGTH;
for (var i = start; i < destinationID.length; i++) {
if (isBoundary(destinationID, i)) {
break;
}
}
return destinationID.substr(0, i);
}
/**
* Gets the nearest common ancestor ID of two IDs.
*
* Using this ID scheme, the nearest common ancestor ID is the longest common
* prefix of the two IDs that immediately preceded a "marker" in both strings.
*
* @param {string} oneID
* @param {string} twoID
* @return {string} Nearest common ancestor ID, or the empty string if none.
* @private
*/
function getFirstCommonAncestorID(oneID, twoID) {
var minLength = Math.min(oneID.length, twoID.length);
if (minLength === 0) {
return '';
}
var lastCommonMarkerIndex = 0;
// Use `<=` to traverse until the "EOL" of the shorter string.
for (var i = 0; i <= minLength; i++) {
if (isBoundary(oneID, i) && isBoundary(twoID, i)) {
lastCommonMarkerIndex = i;
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
break;
}
}
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
invariant(
isValidID(longestCommonID),
'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s',
oneID,
twoID,
longestCommonID
);
return longestCommonID;
}
/**
* Traverses the parent path between two IDs (either up or down). The IDs must
* not be the same, and there must exist a parent path between them.
*
* @param {?string} start ID at which to start traversal.
* @param {?string} stop ID at which to end traversal.
* @param {function} cb Callback to invoke each ID with.
* @param {?boolean} skipFirst Whether or not to skip the first node.
* @param {?boolean} skipLast Whether or not to skip the last node.
* @private
*/
function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
start = start || '';
stop = stop || '';
invariant(
start !== stop,
'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.',
start
);
var traverseUp = isAncestorIDOf(stop, start);
invariant(
traverseUp || isAncestorIDOf(start, stop),
'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' +
'not have a parent path.',
start,
stop
);
// Traverse from `start` to `stop` one depth at a time.
var depth = 0;
var traverse = traverseUp ? getParentID : getNextDescendantID;
for (var id = start; /* until break */; id = traverse(id, stop)) {
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
cb(id, traverseUp, arg);
}
if (id === stop) {
// Only break //after// visiting `stop`.
break;
}
invariant(
depth++ < MAX_TREE_DEPTH,
'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' +
'traversing the React DOM ID tree. This may be due to malformed IDs: %s',
start, stop
);
}
}
/**
* Manages the IDs assigned to DOM representations of React components. This
* uses a specific scheme in order to traverse the DOM efficiently (e.g. in
* order to simulate events).
*
* @internal
*/
var ReactInstanceHandles = {
createReactRootID: function() {
return getReactRootIDString(
Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX)
);
},
/**
* Constructs a React ID by joining a root ID with a name.
*
* @param {string} rootID Root ID of a parent component.
* @param {string} name A component's name (as flattened children).
* @return {string} A React ID.
* @internal
*/
createReactID: function(rootID, name) {
return rootID + SEPARATOR + name;
},
/**
* Gets the DOM ID of the React component that is the root of the tree that
* contains the React component with the supplied DOM ID.
*
* @param {string} id DOM ID of a React component.
* @return {?string} DOM ID of the React component that is the root.
* @internal
*/
getReactRootIDFromNodeID: function(id) {
var regexResult = /\.r\[[^\]]+\]/.exec(id);
return regexResult && regexResult[0];
},
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* NOTE: Does not invoke the callback on the nearest common ancestor because
* nothing "entered" or "left" that element.
*
* @param {string} leaveID ID being left.
* @param {string} enterID ID being entered.
* @param {function} cb Callback to invoke on each entered/left ID.
* @param {*} upArg Argument to invoke the callback with on left IDs.
* @param {*} downArg Argument to invoke the callback with on entered IDs.
* @internal
*/
traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) {
var ancestorID = getFirstCommonAncestorID(leaveID, enterID);
if (ancestorID !== leaveID) {
traverseParentPath(leaveID, ancestorID, cb, upArg, false, true);
}
if (ancestorID !== enterID) {
traverseParentPath(ancestorID, enterID, cb, downArg, true, false);
}
},
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseTwoPhase: function(targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, false);
traverseParentPath(targetID, '', cb, arg, false, true);
}
},
/**
* Exposed for unit testing.
* @private
*/
_getFirstCommonAncestorID: getFirstCommonAncestorID,
/**
* Exposed for unit testing.
* @private
*/
_getNextDescendantID: getNextDescendantID,
isAncestorIDOf: isAncestorIDOf,
SEPARATOR: SEPARATOR
};
module.exports = ReactInstanceHandles;
},{"./invariant":95}],48:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactMarkupChecksum
*/
"use strict";
var adler32 = require("./adler32");
var ReactMarkupChecksum = {
CHECKSUM_ATTR_NAME: 'data-react-checksum',
/**
* @param {string} markup Markup string
* @return {string} Markup string with checksum attribute attached
*/
addChecksumToMarkup: function(markup) {
var checksum = adler32(markup);
return markup.replace(
'>',
' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '">'
);
},
/**
* @param {string} markup to use
* @param {DOMElement} element root React element
* @returns {boolean} whether or not the markup is the same
*/
canReuseMarkup: function(markup, element) {
var existingChecksum = element.getAttribute(
ReactMarkupChecksum.CHECKSUM_ATTR_NAME
);
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
var markupChecksum = adler32(markup);
return markupChecksum === existingChecksum;
}
};
module.exports = ReactMarkupChecksum;
},{"./adler32":75}],49:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactMount
*/
"use strict";
var ReactEventEmitter = require("./ReactEventEmitter");
var ReactInstanceHandles = require("./ReactInstanceHandles");
var $ = require("./$");
var getReactRootElementInContainer = require("./getReactRootElementInContainer");
var invariant = require("./invariant");
var nodeContains = require("./nodeContains");
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var ATTR_NAME = 'data-reactid';
var nodeCache = {};
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
/** Mapping from reactRootID to React component instance. */
var instancesByReactRootID = {};
/** Mapping from reactRootID to `container` nodes. */
var containersByReactRootID = {};
if (true) {
/** __DEV__-only mapping from reactRootID to root elements. */
var rootElementsByReactRootID = {};
}
/**
* @param {DOMElement} container DOM element that may contain a React component.
* @return {?string} A "reactRoot" ID, if a React component is rendered.
*/
function getReactRootID(container) {
var rootElement = getReactRootElementInContainer(container);
return rootElement && ReactMount.getID(rootElement);
}
/**
* Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form
* element can return its control whose name or ID equals ATTR_NAME. All
* DOM nodes support `getAttributeNode` but this can also get called on
* other objects so just return '' if we're given something other than a
* DOM node (such as window).
*
* @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node.
* @return {string} ID of the supplied `domNode`.
*/
function getID(node) {
var id = internalGetID(node);
if (id) {
if (nodeCache.hasOwnProperty(id)) {
var cached = nodeCache[id];
if (cached !== node) {
invariant(
!isValid(cached, id),
'ReactMount: Two valid but unequal nodes with the same `%s`: %s',
ATTR_NAME, id
);
nodeCache[id] = node;
}
} else {
nodeCache[id] = node;
}
}
return id;
}
function internalGetID(node) {
// If node is something like a window, document, or text node, none of
// which support attributes or a .getAttribute method, gracefully return
// the empty string, as if the attribute were missing.
return node && node.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Sets the React-specific ID of the given node.
*
* @param {DOMElement} node The DOM node whose ID will be set.
* @param {string} id The value of the ID attribute.
*/
function setID(node, id) {
var oldID = internalGetID(node);
if (oldID !== id) {
delete nodeCache[oldID];
}
node.setAttribute(ATTR_NAME, id);
nodeCache[id] = node;
}
/**
* Finds the node with the supplied React-generated DOM ID.
*
* @param {string} id A React-generated DOM ID.
* @return {DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNode(id) {
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* A node is "valid" if it is contained by a currently mounted container.
*
* This means that the node does not have to be contained by a document in
* order to be considered valid.
*
* @param {?DOMElement} node The candidate DOM node.
* @param {string} id The expected ID of the node.
* @return {boolean} Whether the node is contained by a mounted container.
*/
function isValid(node, id) {
if (node) {
invariant(
internalGetID(node) === id,
'ReactMount: Unexpected modification of `%s`',
ATTR_NAME
);
var container = ReactMount.findReactContainerForID(id);
if (container && nodeContains(container, node)) {
return true;
}
}
return false;
}
/**
* Causes the cache to forget about one React-specific ID.
*
* @param {string} id The ID to forget.
*/
function purgeID(id) {
delete nodeCache[id];
}
/**
* Mounting is the process of initializing a React component by creatings its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.renderComponent(component, $('container'));
*
* <div id="container"> <-- Supplied `container`.
* <div data-reactid=".r[3]"> <-- Rendered reactRoot of React
* // ... component.
* </div>
* </div>
*
* Inside of `container`, the first element rendered is the "reactRoot".
*/
var ReactMount = {
/**
* Safety guard to prevent accidentally rendering over the entire HTML tree.
*/
allowFullPageRender: false,
/** Time spent generating markup. */
totalInstantiationTime: 0,
/** Time spent inserting markup into the DOM. */
totalInjectionTime: 0,
/** Whether support for touch events should be initialized. */
useTouchEvents: false,
/** Exposed for debugging purposes **/
_instancesByReactRootID: instancesByReactRootID,
/**
* This is a hook provided to support rendering React components while
* ensuring that the apparent scroll position of its `container` does not
* change.
*
* @param {DOMElement} container The `container` being rendered into.
* @param {function} renderCallback This must be called once to do the render.
*/
scrollMonitor: function(container, renderCallback) {
renderCallback();
},
/**
* Ensures that the top-level event delegation listener is set up. This will
* be invoked some time before the first time any React component is rendered.
* @param {DOMElement} container container we're rendering into
*
* @private
*/
prepareEnvironmentForDOM: function(container) {
invariant(
container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
),
'prepareEnvironmentForDOM(...): Target container is not a DOM element.'
);
var doc = container.nodeType === ELEMENT_NODE_TYPE ?
container.ownerDocument :
container;
ReactEventEmitter.ensureListening(ReactMount.useTouchEvents, doc);
},
/**
* Take a component that's already mounted into the DOM and replace its props
* @param {ReactComponent} prevComponent component instance already in the DOM
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function(
prevComponent,
nextComponent,
container,
callback) {
var nextProps = nextComponent.props;
ReactMount.scrollMonitor(container, function() {
prevComponent.replaceProps(nextProps, callback);
});
if (true) {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[getReactRootID(container)] =
getReactRootElementInContainer(container);
}
return prevComponent;
},
/**
* Register a component into the instance map and start the events system.
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @return {string} reactRoot ID prefix
*/
_registerComponent: function(nextComponent, container) {
ReactMount.prepareEnvironmentForDOM(container);
var reactRootID = ReactMount.registerContainer(container);
instancesByReactRootID[reactRootID] = nextComponent;
return reactRootID;
},
/**
* Render a new component into the DOM.
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: function(
nextComponent,
container,
shouldReuseMarkup) {
var reactRootID = ReactMount._registerComponent(nextComponent, container);
nextComponent.mountComponentIntoNode(
reactRootID,
container,
shouldReuseMarkup
);
if (true) {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[reactRootID] =
getReactRootElementInContainer(container);
}
return nextComponent;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactComponent} nextComponent Component instance to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderComponent: function(nextComponent, container, callback) {
var registeredComponent = instancesByReactRootID[getReactRootID(container)];
if (registeredComponent) {
if (registeredComponent.constructor === nextComponent.constructor) {
return ReactMount._updateRootComponent(
registeredComponent,
nextComponent,
container,
callback
);
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup =
reactRootElement && ReactMount.isRenderedByReact(reactRootElement);
var shouldReuseMarkup = containerHasReactMarkup && !registeredComponent;
var component = ReactMount._renderNewRootComponent(
nextComponent,
container,
shouldReuseMarkup
);
callback && callback();
return component;
},
/**
* Constructs a component instance of `constructor` with `initialProps` and
* renders it into the supplied `container`.
*
* @param {function} constructor React component constructor.
* @param {?object} props Initial props of the component instance.
* @param {DOMElement} container DOM element to render into.
* @return {ReactComponent} Component instance rendered in `container`.
*/
constructAndRenderComponent: function(constructor, props, container) {
return ReactMount.renderComponent(constructor(props), container);
},
/**
* Constructs a component instance of `constructor` with `initialProps` and
* renders it into a container node identified by supplied `id`.
*
* @param {function} componentConstructor React component constructor
* @param {?object} props Initial props of the component instance.
* @param {string} id ID of the DOM element to render into.
* @return {ReactComponent} Component instance rendered in the container node.
*/
constructAndRenderComponentByID: function(constructor, props, id) {
return ReactMount.constructAndRenderComponent(constructor, props, $(id));
},
/**
* Registers a container node into which React components will be rendered.
* This also creates the "reatRoot" ID that will be assigned to the element
* rendered within.
*
* @param {DOMElement} container DOM element to register as a container.
* @return {string} The "reactRoot" ID of elements rendered within.
*/
registerContainer: function(container) {
var reactRootID = getReactRootID(container);
if (reactRootID) {
// If one exists, make sure it is a valid "reactRoot" ID.
reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID);
}
if (!reactRootID) {
// No valid "reactRoot" ID found, create one.
reactRootID = ReactInstanceHandles.createReactRootID();
}
containersByReactRootID[reactRootID] = container;
return reactRootID;
},
/**
* Unmounts and destroys the React component rendered in the `container`.
*
* @param {DOMElement} container DOM element containing a React component.
* @return {boolean} True if a component was found in and unmounted from
* `container`
*/
unmountComponentAtNode: function(container) {
var reactRootID = getReactRootID(container);
var component = instancesByReactRootID[reactRootID];
if (!component) {
return false;
}
ReactMount.unmountComponentFromNode(component, container);
delete instancesByReactRootID[reactRootID];
delete containersByReactRootID[reactRootID];
if (true) {
delete rootElementsByReactRootID[reactRootID];
}
return true;
},
/**
* @deprecated
*/
unmountAndReleaseReactRootNode: function() {
if (true) {
console.warn(
'unmountAndReleaseReactRootNode() has been renamed to ' +
'unmountComponentAtNode() and will be removed in the next ' +
'version of React.'
);
}
return ReactMount.unmountComponentAtNode.apply(this, arguments);
},
/**
* Unmounts a component and removes it from the DOM.
*
* @param {ReactComponent} instance React component instance.
* @param {DOMElement} container DOM element to unmount from.
* @final
* @internal
* @see {ReactMount.unmountComponentAtNode}
*/
unmountComponentFromNode: function(instance, container) {
instance.unmountComponent();
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
},
/**
* Finds the container DOM element that contains React component to which the
* supplied DOM `id` belongs.
*
* @param {string} id The ID of an element rendered by a React component.
* @return {?DOMElement} DOM element that contains the `id`.
*/
findReactContainerForID: function(id) {
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id);
var container = containersByReactRootID[reactRootID];
if (true) {
var rootElement = rootElementsByReactRootID[reactRootID];
if (rootElement && rootElement.parentNode !== container) {
invariant(
// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID,
'ReactMount: Root element ID differed from reactRootID.'
);
var containerChild = container.firstChild;
if (containerChild &&
reactRootID === internalGetID(containerChild)) {
// If the container has a new child with the same ID as the old
// root element, then rootElementsByReactRootID[reactRootID] is
// just stale and needs to be updated. The case that deserves a
// warning is when the container is empty.
rootElementsByReactRootID[reactRootID] = containerChild;
} else {
console.warn(
'ReactMount: Root element has been removed from its original ' +
'container. New container:', rootElement.parentNode
);
}
}
}
return container;
},
/**
* Finds an element rendered by React with the supplied ID.
*
* @param {string} id ID of a DOM node in the React component.
* @return {DOMElement} Root DOM node of the React component.
*/
findReactNodeByID: function(id) {
var reactRoot = ReactMount.findReactContainerForID(id);
return ReactMount.findComponentRoot(reactRoot, id);
},
/**
* True if the supplied `node` is rendered by React.
*
* @param {*} node DOM Element to check.
* @return {boolean} True if the DOM Element appears to be rendered by React.
* @internal
*/
isRenderedByReact: function(node) {
if (node.nodeType !== 1) {
// Not a DOMElement, therefore not a React component
return false;
}
var id = ReactMount.getID(node);
return id ? id.charAt(0) === SEPARATOR : false;
},
/**
* Traverses up the ancestors of the supplied node to find a node that is a
* DOM representation of a React component.
*
* @param {*} node
* @return {?DOMEventTarget}
* @internal
*/
getFirstReactDOM: function(node) {
var current = node;
while (current && current.parentNode !== current) {
if (ReactMount.isRenderedByReact(current)) {
return current;
}
current = current.parentNode;
}
return null;
},
/**
* Finds a node with the supplied `id` inside of the supplied `ancestorNode`.
* Exploits the ID naming scheme to perform the search quickly.
*
* @param {DOMEventTarget} ancestorNode Search from this root.
* @pararm {string} id ID of the DOM representation of the component.
* @return {DOMEventTarget} DOM node with the supplied `id`.
* @internal
*/
findComponentRoot: function(ancestorNode, id) {
var firstChildren = [ancestorNode.firstChild];
var childIndex = 0;
while (childIndex < firstChildren.length) {
var child = firstChildren[childIndex++];
while (child) {
var childID = ReactMount.getID(child);
if (childID) {
if (id === childID) {
return child;
} else if (ReactInstanceHandles.isAncestorIDOf(childID, id)) {
// If we find a child whose ID is an ancestor of the given ID,
// then we can be sure that we only want to search the subtree
// rooted at this child, so we can throw out the rest of the
// search state.
firstChildren.length = childIndex = 0;
firstChildren.push(child.firstChild);
break;
} else {
// TODO This should not be necessary if the ID hierarchy is
// correct, but is occasionally necessary if the DOM has been
// modified in unexpected ways.
firstChildren.push(child.firstChild);
}
} else {
// If this child had no ID, then there's a chance that it was
// injected automatically by the browser, as when a `<table>`
// element sprouts an extra `<tbody>` child as a side effect of
// `.innerHTML` parsing. Optimistically continue down this
// branch, but not before examining the other siblings.
firstChildren.push(child.firstChild);
}
child = child.nextSibling;
}
}
if (true) {
console.error(
'Error while invoking `findComponentRoot` with the following ' +
'ancestor node:',
ancestorNode
);
}
invariant(
false,
'findComponentRoot(..., %s): Unable to find element. This probably ' +
'means the DOM was unexpectedly mutated (e.g. by the browser).',
id,
ReactMount.getID(ancestorNode)
);
},
/**
* React ID utilities.
*/
ATTR_NAME: ATTR_NAME,
getReactRootID: getReactRootID,
getID: getID,
setID: setID,
getNode: getNode,
purgeID: purgeID,
injection: {}
};
module.exports = ReactMount;
},{"./$":1,"./ReactEventEmitter":43,"./ReactInstanceHandles":47,"./getReactRootElementInContainer":92,"./invariant":95,"./nodeContains":109}],50:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactMountReady
*/
"use strict";
var PooledClass = require("./PooledClass");
var mixInto = require("./mixInto");
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `ReactMountReady.getPooled()`.
*
* @param {?array<function>} initialCollection
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
function ReactMountReady(initialCollection) {
this._queue = initialCollection || null;
}
mixInto(ReactMountReady, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked. This is used
* to enqueue calls to `componentDidMount` and `componentDidUpdate`.
*
* @param {ReactComponent} component Component being rendered.
* @param {function(DOMElement)} callback Invoked when `notifyAll` is invoked.
* @internal
*/
enqueue: function(component, callback) {
this._queue = this._queue || [];
this._queue.push({component: component, callback: callback});
},
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
notifyAll: function() {
var queue = this._queue;
if (queue) {
this._queue = null;
for (var i = 0, l = queue.length; i < l; i++) {
var component = queue[i].component;
var callback = queue[i].callback;
callback.call(component, component.getDOMNode());
}
queue.length = 0;
}
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function() {
this._queue = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function() {
this.reset();
}
});
PooledClass.addPoolingTo(ReactMountReady);
module.exports = ReactMountReady;
},{"./PooledClass":23,"./mixInto":107}],51:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactMultiChild
* @typechecks static-only
*/
"use strict";
var ReactComponent = require("./ReactComponent");
var ReactMultiChildUpdateTypes = require("./ReactMultiChildUpdateTypes");
var flattenChildren = require("./flattenChildren");
/**
* Given a `curChild` and `newChild`, determines if `curChild` should be
* updated as opposed to being destroyed or replaced.
*
* @param {?ReactComponent} curChild
* @param {?ReactComponent} newChild
* @return {boolean} True if `curChild` should be updated with `newChild`.
* @protected
*/
function shouldUpdateChild(curChild, newChild) {
return curChild && newChild && curChild.constructor === newChild.constructor;
}
/**
* Updating children of a component may trigger recursive updates. The depth is
* used to batch recursive updates to render markup more efficiently.
*
* @type {number}
* @private
*/
var updateDepth = 0;
/**
* Queue of update configuration objects.
*
* Each object has a `type` property that is in `ReactMultiChildUpdateTypes`.
*
* @type {array<object>}
* @private
*/
var updateQueue = [];
/**
* Queue of markup to be rendered.
*
* @type {array<string>}
* @private
*/
var markupQueue = [];
/**
* Enqueues markup to be rendered and inserted at a supplied index.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function enqueueMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
fromIndex: null,
textContent: null,
toIndex: toIndex
});
}
/**
* Enqueues moving an existing element to another index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function enqueueMove(parentID, fromIndex, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
markupIndex: null,
textContent: null,
fromIndex: fromIndex,
toIndex: toIndex
});
}
/**
* Enqueues removing an element at an index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function enqueueRemove(parentID, fromIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
markupIndex: null,
textContent: null,
fromIndex: fromIndex,
toIndex: null
});
}
/**
* Enqueues setting the text content.
*
* @param {string} parentID ID of the parent component.
* @param {string} textContent Text content to set.
* @private
*/
function enqueueTextContent(parentID, textContent) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
markupIndex: null,
textContent: textContent,
fromIndex: null,
toIndex: null
});
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue() {
if (updateQueue.length) {
ReactComponent.DOMIDOperations.dangerouslyProcessChildrenUpdates(
updateQueue,
markupQueue
);
clearQueue();
}
}
/**
* Clears any enqueued updates.
*
* @private
*/
function clearQueue() {
updateQueue.length = 0;
markupQueue.length = 0;
}
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function(nestedChildren, transaction) {
var children = flattenChildren(nestedChildren);
var mountImages = [];
var index = 0;
this._renderedChildren = children;
for (var name in children) {
var child = children[name];
if (children.hasOwnProperty(name) && child) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + '.' + name;
var mountImage = child.mountComponent(
rootID,
transaction,
this._mountDepth + 1
);
child._mountImage = mountImage;
child._mountIndex = index;
mountImages.push(mountImage);
index++;
}
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function(nextContent) {
updateDepth++;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name) &&
prevChildren[name]) {
this._unmountChildByName(prevChildren[name], name);
}
}
// Set new text content.
this.setTextContent(nextContent);
} catch (error) {
updateDepth--;
updateDepth || clearQueue();
throw error;
}
updateDepth--;
updateDepth || processQueue();
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function(nextNestedChildren, transaction) {
updateDepth++;
try {
this._updateChildren(nextNestedChildren, transaction);
} catch (error) {
updateDepth--;
updateDepth || clearQueue();
throw error;
}
updateDepth--;
updateDepth || processQueue();
},
/**
* Improve performance by isolating this hot code path from the try/catch
* block in `updateChildren`.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function(nextNestedChildren, transaction) {
var nextChildren = flattenChildren(nextNestedChildren);
var prevChildren = this._renderedChildren;
if (!nextChildren && !prevChildren) {
return;
}
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var lastIndex = 0;
var nextIndex = 0;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var nextChild = nextChildren[name];
if (shouldUpdateChild(prevChild, nextChild)) {
this.moveChild(prevChild, nextIndex, lastIndex);
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild.receiveProps(nextChild.props, transaction);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
this._unmountChildByName(prevChild, name);
}
if (nextChild) {
this._mountChildByNameAtIndex(
nextChild, name, nextIndex, transaction
);
}
}
if (nextChild) {
nextIndex++;
}
}
// Remove children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) &&
prevChildren[name] &&
!(nextChildren && nextChildren[name])) {
this._unmountChildByName(prevChildren[name], name);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @internal
*/
unmountChildren: function() {
var renderedChildren = this._renderedChildren;
for (var name in renderedChildren) {
var renderedChild = renderedChildren[name];
if (renderedChild && renderedChild.unmountComponent) {
renderedChild.unmountComponent();
}
}
this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function(child, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
if (child._mountIndex < lastIndex) {
enqueueMove(this._rootNodeID, child._mountIndex, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @protected
*/
createChild: function(child) {
enqueueMarkup(this._rootNodeID, child._mountImage, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function(child) {
enqueueRemove(this._rootNodeID, child._mountIndex);
},
/**
* Sets this text content string.
*
* @param {string} textContent Text content to set.
* @protected
*/
setTextContent: function(textContent) {
enqueueTextContent(this._rootNodeID, textContent);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildByNameAtIndex: function(child, name, index, transaction) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + '.' + name;
var mountImage = child.mountComponent(
rootID,
transaction,
this._mountDepth + 1
);
child._mountImage = mountImage;
child._mountIndex = index;
this.createChild(child);
this._renderedChildren = this._renderedChildren || {};
this._renderedChildren[name] = child;
},
/**
* Unmounts a rendered child by name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @param {string} name Name of the child in `this._renderedChildren`.
* @private
*/
_unmountChildByName: function(child, name) {
if (ReactComponent.isValidComponent(child)) {
this.removeChild(child);
child._mountImage = null;
child._mountIndex = null;
child.unmountComponent();
delete this._renderedChildren[name];
}
}
}
};
module.exports = ReactMultiChild;
},{"./ReactComponent":25,"./ReactMultiChildUpdateTypes":52,"./flattenChildren":85}],52:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactMultiChildUpdateTypes
*/
var keyMirror = require("./keyMirror");
/**
* When a component's children are updated, a series of update configuration
* objects are created in order to batch and serialize the required changes.
*
* Enumerates all the possible types of update configurations.
*
* @internal
*/
var ReactMultiChildUpdateTypes = keyMirror({
INSERT_MARKUP: null,
MOVE_EXISTING: null,
REMOVE_NODE: null,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
},{"./keyMirror":101}],53:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactOwner
*/
"use strict";
var invariant = require("./invariant");
/**
* ReactOwners are capable of storing references to owned components.
*
* All components are capable of //being// referenced by owner components, but
* only ReactOwner components are capable of //referencing// owned components.
* The named reference is known as a "ref".
*
* Refs are available when mounted and updated during reconciliation.
*
* var MyComponent = React.createClass({
* render: function() {
* return (
* <div onClick={this.handleClick}>
* <CustomComponent ref="custom" />
* </div>
* );
* },
* handleClick: function() {
* this.refs.custom.handleClick();
* },
* componentDidMount: function() {
* this.refs.custom.initialize();
* }
* });
*
* Refs should rarely be used. When refs are used, they should only be done to
* control data that is not handled by React's data flow.
*
* @class ReactOwner
*/
var ReactOwner = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
isValidOwner: function(object) {
return !!(
object &&
typeof object.attachRef === 'function' &&
typeof object.detachRef === 'function'
);
},
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function(component, ref, owner) {
invariant(
ReactOwner.isValidOwner(owner),
'addComponentAsRefTo(...): Only a ReactOwner can have refs.'
);
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function(component, ref, owner) {
invariant(
ReactOwner.isValidOwner(owner),
'removeComponentAsRefFrom(...): Only a ReactOwner can have refs.'
);
// Check that `component` is still the current ref because we do not want to
// detach the ref if another component stole it.
if (owner.refs[ref] === component) {
owner.detachRef(ref);
}
},
/**
* A ReactComponent must mix this in to have refs.
*
* @lends {ReactOwner.prototype}
*/
Mixin: {
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function(ref, component) {
invariant(
component.isOwnedBy(this),
'attachRef(%s, ...): Only a component\'s owner can store a ref to it.',
ref
);
var refs = this.refs || (this.refs = {});
refs[ref] = component;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function(ref) {
delete this.refs[ref];
}
}
};
module.exports = ReactOwner;
},{"./invariant":95}],54:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactPerf
* @typechecks static-only
*/
"use strict";
var ReactPerf = {
/**
* Boolean to enable/disable measurement. Set to false by default to prevent
* accidental logging and perf loss.
*/
enableMeasure: false,
/**
* Holds onto the measure function in use. By default, don't measure
* anything, but we'll override this if we inject a measure function.
*/
storedMeasure: _noMeasure,
/**
* Use this to wrap methods you want to measure.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
measure: function(objName, fnName, func) {
if (true) {
var measuredFunc = null;
return function() {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
};
}
return func;
},
injection: {
/**
* @param {function} measure
*/
injectMeasure: function(measure) {
ReactPerf.storedMeasure = measure;
}
}
};
if (true) {
var ExecutionEnvironment = require("./ExecutionEnvironment");
var URL = ExecutionEnvironment.canUseDOM ? window.location.href : '';
ReactPerf.enableMeasure = ReactPerf.enableMeasure ||
!!URL.match(/[?&]react_perf\b/);
}
/**
* Simply passes through the measured function, without measuring it.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
function _noMeasure(objName, fnName, func) {
return func;
}
module.exports = ReactPerf;
},{"./ExecutionEnvironment":20}],55:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactPropTransferer
*/
"use strict";
var emptyFunction = require("./emptyFunction");
var invariant = require("./invariant");
var joinClasses = require("./joinClasses");
var merge = require("./merge");
/**
* Creates a transfer strategy that will merge prop values using the supplied
* `mergeStrategy`. If a prop was previously unset, this just sets it.
*
* @param {function} mergeStrategy
* @return {function}
*/
function createTransferStrategy(mergeStrategy) {
return function(props, key, value) {
if (!props.hasOwnProperty(key)) {
props[key] = value;
} else {
props[key] = mergeStrategy(props[key], value);
}
};
}
/**
* Transfer strategies dictate how props are transferred by `transferPropsTo`.
*/
var TransferStrategies = {
/**
* Never transfer `children`.
*/
children: emptyFunction,
/**
* Transfer the `className` prop by merging them.
*/
className: createTransferStrategy(joinClasses),
/**
* Never transfer the `ref` prop.
*/
ref: emptyFunction,
/**
* Transfer the `style` prop (which is an object) by merging them.
*/
style: createTransferStrategy(merge)
};
/**
* ReactPropTransferer are capable of transferring props to another component
* using a `transferPropsTo` method.
*
* @class ReactPropTransferer
*/
var ReactPropTransferer = {
TransferStrategies: TransferStrategies,
/**
* @lends {ReactPropTransferer.prototype}
*/
Mixin: {
/**
* Transfer props from this component to a target component.
*
* Props that do not have an explicit transfer strategy will be transferred
* only if the target component does not already have the prop set.
*
* This is usually used to pass down props to a returned root component.
*
* @param {ReactComponent} component Component receiving the properties.
* @return {ReactComponent} The supplied `component`.
* @final
* @protected
*/
transferPropsTo: function(component) {
invariant(
component.props.__owner__ === this,
'%s: You can\'t call transferPropsTo() on a component that you ' +
'don\'t own, %s. This usually means you are calling ' +
'transferPropsTo() on a component passed in as props or children.',
this.constructor.displayName,
component.constructor.displayName
);
var props = {};
for (var thatKey in component.props) {
if (component.props.hasOwnProperty(thatKey)) {
props[thatKey] = component.props[thatKey];
}
}
for (var thisKey in this.props) {
if (!this.props.hasOwnProperty(thisKey)) {
continue;
}
var transferStrategy = TransferStrategies[thisKey];
if (transferStrategy) {
transferStrategy(props, thisKey, this.props[thisKey]);
} else if (!props.hasOwnProperty(thisKey)) {
props[thisKey] = this.props[thisKey];
}
}
component.props = props;
return component;
}
}
};
module.exports = ReactPropTransferer;
},{"./emptyFunction":81,"./invariant":95,"./joinClasses":100,"./merge":104}],56:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactPropTypes
*/
"use strict";
var createObjectFrom = require("./createObjectFrom");
var invariant = require("./invariant");
/**
* 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 Props = require('ReactPropTypes');
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* invariant(
* propValue == null ||
* typeof propValue === 'string' ||
* propValue instanceof URI,
* 'Invalid `%s` supplied to `%s`, expected string or URI.',
* propName,
* componentName
* );
* }
* },
* render: function() { ... }
* });
*
* @internal
*/
var Props = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
oneOf: createEnumTypeChecker,
instanceOf: createInstanceTypeChecker
};
var ANONYMOUS = '<<anonymous>>';
function createPrimitiveTypeChecker(expectedType) {
function validatePrimitiveType(propValue, propName, componentName) {
var propType = typeof propValue;
if (propType === 'object' && Array.isArray(propValue)) {
propType = 'array';
}
invariant(
propType === expectedType,
'Invalid prop `%s` of type `%s` supplied to `%s`, expected `%s`.',
propName,
propType,
componentName,
expectedType
);
}
return createChainableTypeChecker(validatePrimitiveType);
}
function createEnumTypeChecker(expectedValues) {
var expectedEnum = createObjectFrom(expectedValues);
function validateEnumType(propValue, propName, componentName) {
invariant(
expectedEnum[propValue],
'Invalid prop `%s` supplied to `%s`, expected one of %s.',
propName,
componentName,
JSON.stringify(Object.keys(expectedEnum))
);
}
return createChainableTypeChecker(validateEnumType);
}
function createInstanceTypeChecker(expectedClass) {
function validateInstanceType(propValue, propName, componentName) {
invariant(
propValue instanceof expectedClass,
'Invalid prop `%s` supplied to `%s`, expected instance of `%s`.',
propName,
componentName,
expectedClass.name || ANONYMOUS
);
}
return createChainableTypeChecker(validateInstanceType);
}
function createChainableTypeChecker(validate) {
function createTypeChecker(isRequired) {
function checkType(props, propName, componentName) {
var propValue = props[propName];
if (propValue != null) {
// Only validate if there is a value to check.
validate(propValue, propName, componentName || ANONYMOUS);
} else {
invariant(
!isRequired,
'Required prop `%s` was not specified in `%s`.',
propName,
componentName || ANONYMOUS
);
}
}
if (!isRequired) {
checkType.isRequired = createTypeChecker(true);
}
return checkType;
}
return createTypeChecker(false);
}
module.exports = Props;
},{"./createObjectFrom":79,"./invariant":95}],57:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactReconcileTransaction
* @typechecks static-only
*/
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
var PooledClass = require("./PooledClass");
var ReactEventEmitter = require("./ReactEventEmitter");
var ReactInputSelection = require("./ReactInputSelection");
var ReactMountReady = require("./ReactMountReady");
var Transaction = require("./Transaction");
var mixInto = require("./mixInto");
/**
* Ensures that, when possible, the selection range (currently selected text
* input) is not disturbed by performing the transaction.
*/
var SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
};
/**
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
* high level DOM manipulations (like temporarily removing a text input from the
* DOM).
*/
var EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactEventEmitter` before the
* reconciliation.
*/
initialize: function() {
var currentlyEnabled = ReactEventEmitter.isEnabled();
ReactEventEmitter.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of `ReactEventEmitter`
* before the reconciliation occured. `close` restores the previous value.
*/
close: function(previouslyEnabled) {
ReactEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a `ReactMountReady` queue for collecting `onDOMReady` callbacks
* during the performing of the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function() {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function() {
this.reactMountReady.notifyAll();
}
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [
SELECTION_RESTORATION,
EVENT_SUPPRESSION,
ON_DOM_READY_QUEUEING
];
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction() {
this.reinitializeTransaction();
this.reactMountReady = ReactMountReady.getPooled(null);
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap proceedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function() {
if (ExecutionEnvironment.canUseDOM) {
return TRANSACTION_WRAPPERS;
} else {
return [];
}
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
* TODO: convert to ReactMountReady
*/
getReactMountReady: function() {
return this.reactMountReady;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be resused.
*/
destructor: function() {
ReactMountReady.release(this.reactMountReady);
this.reactMountReady = null;
}
};
mixInto(ReactReconcileTransaction, Transaction.Mixin);
mixInto(ReactReconcileTransaction, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
},{"./ExecutionEnvironment":20,"./PooledClass":23,"./ReactEventEmitter":43,"./ReactInputSelection":46,"./ReactMountReady":50,"./Transaction":72,"./mixInto":107}],58:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @typechecks static-only
* @providesModule ReactServerRendering
*/
"use strict";
var ReactMarkupChecksum = require("./ReactMarkupChecksum");
var ReactReconcileTransaction = require("./ReactReconcileTransaction");
var ReactInstanceHandles = require("./ReactInstanceHandles");
/**
* @param {object} component
* @param {function} callback
*/
function renderComponentToString(component, callback) {
// We use a callback API to keep the API async in case in the future we ever
// need it, but in reality this is a synchronous operation.
var id = ReactInstanceHandles.createReactRootID();
var transaction = ReactReconcileTransaction.getPooled();
transaction.reinitializeTransaction();
try {
transaction.perform(function() {
var markup = component.mountComponent(id, transaction, 0);
markup = ReactMarkupChecksum.addChecksumToMarkup(markup);
callback(markup);
}, null);
} finally {
ReactReconcileTransaction.release(transaction);
}
}
module.exports = {
renderComponentToString: renderComponentToString
};
},{"./ReactInstanceHandles":47,"./ReactMarkupChecksum":48,"./ReactReconcileTransaction":57}],59:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactTextComponent
* @typechecks static-only
*/
"use strict";
var ReactComponent = require("./ReactComponent");
var ReactMount = require("./ReactMount");
var escapeTextForBrowser = require("./escapeTextForBrowser");
var mixInto = require("./mixInto");
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings in elements so that they can undergo
* the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactTextComponent
* @extends ReactComponent
* @internal
*/
var ReactTextComponent = function(initialText) {
this.construct({text: initialText});
};
mixInto(ReactTextComponent, ReactComponent.Mixin);
mixInto(ReactTextComponent, {
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
return (
'<span ' + ReactMount.ATTR_NAME + '="' + escapeTextForBrowser(rootID) + '">' +
escapeTextForBrowser(this.props.text) +
'</span>'
);
},
/**
* Updates this component by updating the text content.
*
* @param {object} nextProps Contains the next text content.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveProps: function(nextProps, transaction) {
if (nextProps.text !== this.props.text) {
this.props.text = nextProps.text;
ReactComponent.DOMIDOperations.updateTextContentByID(
this._rootNodeID,
nextProps.text
);
}
}
});
module.exports = ReactTextComponent;
},{"./ReactComponent":25,"./ReactMount":49,"./escapeTextForBrowser":82,"./mixInto":107}],60:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactUpdates
*/
"use strict";
var invariant = require("./invariant");
var dirtyComponents = [];
var batchingStrategy = null;
function ensureBatchingStrategy() {
invariant(batchingStrategy, 'ReactUpdates: must inject a batching strategy');
}
function batchedUpdates(callback, param) {
ensureBatchingStrategy();
batchingStrategy.batchedUpdates(callback, param);
}
/**
* Array comparator for ReactComponents by owner depth
*
* @param {ReactComponent} c1 first component you're comparing
* @param {ReactComponent} c2 second component you're comparing
* @return {number} Return value usable by Array.prototype.sort().
*/
function mountDepthComparator(c1, c2) {
return c1._mountDepth - c2._mountDepth;
}
function runBatchedUpdates() {
// Since reconciling a component higher in the owner hierarchy usually (not
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
// them before their children by sorting the array.
dirtyComponents.sort(mountDepthComparator);
for (var i = 0; i < dirtyComponents.length; i++) {
// If a component is unmounted before pending changes apply, ignore them
// TODO: Queue unmounts in the same list to avoid this happening at all
var component = dirtyComponents[i];
if (component.isMounted()) {
// If performUpdateIfNecessary happens to enqueue any new updates, we
// shouldn't execute the callbacks until the next render happens, so
// stash the callbacks first
var callbacks = component._pendingCallbacks;
component._pendingCallbacks = null;
component.performUpdateIfNecessary();
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
callbacks[j].call(component);
}
}
}
}
}
function clearDirtyComponents() {
dirtyComponents.length = 0;
}
function flushBatchedUpdates() {
// Run these in separate functions so the JIT can optimize
try {
runBatchedUpdates();
} catch (e) {
// IE 8 requires catch to use finally.
throw e;
} finally {
clearDirtyComponents();
}
}
/**
* Mark a component as needing a rerender, adding an optional callback to a
* list of functions which will be executed once the rerender occurs.
*/
function enqueueUpdate(component, callback) {
invariant(
!callback || typeof callback === "function",
'enqueueUpdate(...): You called `setProps`, `replaceProps`, ' +
'`setState`, `replaceState`, or `forceUpdate` with a callback that ' +
'isn\'t callable.'
);
ensureBatchingStrategy();
if (!batchingStrategy.isBatchingUpdates) {
component.performUpdateIfNecessary();
callback && callback();
return;
}
dirtyComponents.push(component);
if (callback) {
if (component._pendingCallbacks) {
component._pendingCallbacks.push(callback);
} else {
component._pendingCallbacks = [callback];
}
}
}
var ReactUpdatesInjection = {
injectBatchingStrategy: function(_batchingStrategy) {
invariant(
_batchingStrategy,
'ReactUpdates: must provide a batching strategy'
);
invariant(
typeof _batchingStrategy.batchedUpdates === 'function',
'ReactUpdates: must provide a batchedUpdates() function'
);
invariant(
typeof _batchingStrategy.isBatchingUpdates === 'boolean',
'ReactUpdates: must provide an isBatchingUpdates boolean attribute'
);
batchingStrategy = _batchingStrategy;
}
};
var ReactUpdates = {
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection
};
module.exports = ReactUpdates;
},{"./invariant":95}],61:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SelectEventPlugin
*/
"use strict";
var EventConstants = require("./EventConstants");
var EventPluginHub = require("./EventPluginHub");
var EventPropagators = require("./EventPropagators");
var ExecutionEnvironment = require("./ExecutionEnvironment");
var ReactInputSelection = require("./ReactInputSelection");
var SyntheticEvent = require("./SyntheticEvent");
var getActiveElement = require("./getActiveElement");
var isEventSupported = require("./isEventSupported");
var isTextInputElement = require("./isTextInputElement");
var keyOf = require("./keyOf");
var shallowEqual = require("./shallowEqual");
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
select: {
phasedRegistrationNames: {
bubbled: keyOf({onSelect: null}),
captured: keyOf({onSelectCapture: null})
}
}
};
var useSelectionChange = false;
var useSelect = false;
if (ExecutionEnvironment.canUseDOM) {
useSelectionChange = 'onselectionchange' in document;
useSelect = isEventSupported('select');
}
var activeElement = null;
var activeElementID = null;
var activeNativeEvent = null;
var lastSelection = null;
var mouseDown = false;
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*
* @param {DOMElement} node
* @param {object}
*/
function getSelection(node) {
if ('selectionStart' in node &&
ReactInputSelection.hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
} else {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior).
if (mouseDown || activeElement != getActiveElement()) {
return;
}
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(
eventTypes.select,
activeElementID,
nativeEvent
);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
}
/**
* Handle deferred event. And manually dispatch synthetic events.
*/
function dispatchDeferredSelectEvent() {
if (!activeNativeEvent) {
return;
}
var syntheticEvent = constructSelectEvent(activeNativeEvent);
activeNativeEvent = null;
// Enqueue and process the abstract event manually.
if (syntheticEvent) {
EventPluginHub.enqueueEvents(syntheticEvent);
EventPluginHub.processEventQueue();
}
}
/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/
var SelectEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
if (isTextInputElement(topLevelTarget) ||
topLevelTarget.contentEditable === 'true') {
activeElement = topLevelTarget;
activeElementID = topLevelTargetID;
lastSelection = null;
}
break;
case topLevelTypes.topBlur:
activeElement = null;
activeElementID = null;
lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case topLevelTypes.topMouseDown:
mouseDown = true;
break;
case topLevelTypes.topMouseUp:
mouseDown = false;
return constructSelectEvent(nativeEvent);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't).
case topLevelTypes.topSelectionChange:
return constructSelectEvent(nativeEvent);
// Firefox doesn't support selectionchange, so check selection status
// after each key entry.
case topLevelTypes.topKeyDown:
if (!useSelectionChange) {
activeNativeEvent = nativeEvent;
setTimeout(dispatchDeferredSelectEvent, 0);
}
break;
}
}
};
module.exports = SelectEventPlugin;
},{"./EventConstants":14,"./EventPluginHub":16,"./EventPropagators":19,"./ExecutionEnvironment":20,"./ReactInputSelection":46,"./SyntheticEvent":65,"./getActiveElement":88,"./isEventSupported":96,"./isTextInputElement":98,"./keyOf":102,"./shallowEqual":113}],62:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SimpleEventPlugin
*/
"use strict";
var EventConstants = require("./EventConstants");
var EventPropagators = require("./EventPropagators");
var SyntheticClipboardEvent = require("./SyntheticClipboardEvent");
var SyntheticEvent = require("./SyntheticEvent");
var SyntheticFocusEvent = require("./SyntheticFocusEvent");
var SyntheticKeyboardEvent = require("./SyntheticKeyboardEvent");
var SyntheticMouseEvent = require("./SyntheticMouseEvent");
var SyntheticTouchEvent = require("./SyntheticTouchEvent");
var SyntheticUIEvent = require("./SyntheticUIEvent");
var SyntheticWheelEvent = require("./SyntheticWheelEvent");
var invariant = require("./invariant");
var keyOf = require("./keyOf");
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
blur: {
phasedRegistrationNames: {
bubbled: keyOf({onBlur: true}),
captured: keyOf({onBlurCapture: true})
}
},
click: {
phasedRegistrationNames: {
bubbled: keyOf({onClick: true}),
captured: keyOf({onClickCapture: true})
}
},
copy: {
phasedRegistrationNames: {
bubbled: keyOf({onCopy: true}),
captured: keyOf({onCopyCapture: true})
}
},
cut: {
phasedRegistrationNames: {
bubbled: keyOf({onCut: true}),
captured: keyOf({onCutCapture: true})
}
},
doubleClick: {
phasedRegistrationNames: {
bubbled: keyOf({onDoubleClick: true}),
captured: keyOf({onDoubleClickCapture: true})
}
},
drag: {
phasedRegistrationNames: {
bubbled: keyOf({onDrag: true}),
captured: keyOf({onDragCapture: true})
}
},
dragEnd: {
phasedRegistrationNames: {
bubbled: keyOf({onDragEnd: true}),
captured: keyOf({onDragEndCapture: true})
}
},
dragEnter: {
phasedRegistrationNames: {
bubbled: keyOf({onDragEnter: true}),
captured: keyOf({onDragEnterCapture: true})
}
},
dragExit: {
phasedRegistrationNames: {
bubbled: keyOf({onDragExit: true}),
captured: keyOf({onDragExitCapture: true})
}
},
dragLeave: {
phasedRegistrationNames: {
bubbled: keyOf({onDragLeave: true}),
captured: keyOf({onDragLeaveCapture: true})
}
},
dragOver: {
phasedRegistrationNames: {
bubbled: keyOf({onDragOver: true}),
captured: keyOf({onDragOverCapture: true})
}
},
dragStart: {
phasedRegistrationNames: {
bubbled: keyOf({onDragStart: true}),
captured: keyOf({onDragStartCapture: true})
}
},
drop: {
phasedRegistrationNames: {
bubbled: keyOf({onDrop: true}),
captured: keyOf({onDropCapture: true})
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({onFocus: true}),
captured: keyOf({onFocusCapture: true})
}
},
input: {
phasedRegistrationNames: {
bubbled: keyOf({onInput: true}),
captured: keyOf({onInputCapture: true})
}
},
keyDown: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyDown: true}),
captured: keyOf({onKeyDownCapture: true})
}
},
keyPress: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyPress: true}),
captured: keyOf({onKeyPressCapture: true})
}
},
keyUp: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyUp: true}),
captured: keyOf({onKeyUpCapture: true})
}
},
// Note: We do not allow listening to mouseOver events. Instead, use the
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
mouseDown: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseDown: true}),
captured: keyOf({onMouseDownCapture: true})
}
},
mouseMove: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseMove: true}),
captured: keyOf({onMouseMoveCapture: true})
}
},
mouseUp: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseUp: true}),
captured: keyOf({onMouseUpCapture: true})
}
},
paste: {
phasedRegistrationNames: {
bubbled: keyOf({onPaste: true}),
captured: keyOf({onPasteCapture: true})
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({onScroll: true}),
captured: keyOf({onScrollCapture: true})
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({onSubmit: true}),
captured: keyOf({onSubmitCapture: true})
}
},
touchCancel: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchCancel: true}),
captured: keyOf({onTouchCancelCapture: true})
}
},
touchEnd: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchEnd: true}),
captured: keyOf({onTouchEndCapture: true})
}
},
touchMove: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchMove: true}),
captured: keyOf({onTouchMoveCapture: true})
}
},
touchStart: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchStart: true}),
captured: keyOf({onTouchStartCapture: true})
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({onWheel: true}),
captured: keyOf({onWheelCapture: true})
}
}
};
var topLevelEventsToDispatchConfig = {
topBlur: eventTypes.blur,
topClick: eventTypes.click,
topCopy: eventTypes.copy,
topCut: eventTypes.cut,
topDoubleClick: eventTypes.doubleClick,
topDrag: eventTypes.drag,
topDragEnd: eventTypes.dragEnd,
topDragEnter: eventTypes.dragEnter,
topDragExit: eventTypes.dragExit,
topDragLeave: eventTypes.dragLeave,
topDragOver: eventTypes.dragOver,
topDragStart: eventTypes.dragStart,
topDrop: eventTypes.drop,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topScroll: eventTypes.scroll,
topSubmit: eventTypes.submit,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topWheel: eventTypes.wheel
};
var SimpleEventPlugin = {
eventTypes: eventTypes,
/**
* Same as the default implementation, except cancels the event when return
* value is false.
*
* @param {object} Event to be dispatched.
* @param {function} Application-level callback.
* @param {string} domID DOM ID to pass to the callback.
*/
executeDispatch: function(event, listener, domID) {
var returnValue = listener(event, domID);
if (returnValue === false) {
event.stopPropagation();
event.preventDefault();
}
},
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch(topLevelType) {
case topLevelTypes.topInput:
case topLevelTypes.topSubmit:
// HTML Events
// @see http://www.w3.org/TR/html5/index.html#events-0
EventConstructor = SyntheticEvent;
break;
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyPress:
case topLevelTypes.topKeyUp:
EventConstructor = SyntheticKeyboardEvent;
break;
case topLevelTypes.topBlur:
case topLevelTypes.topFocus:
EventConstructor = SyntheticFocusEvent;
break;
case topLevelTypes.topClick:
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (nativeEvent.button === 2) {
return null;
}
/* falls through */
case topLevelTypes.topDoubleClick:
case topLevelTypes.topDrag:
case topLevelTypes.topDragEnd:
case topLevelTypes.topDragEnter:
case topLevelTypes.topDragExit:
case topLevelTypes.topDragLeave:
case topLevelTypes.topDragOver:
case topLevelTypes.topDragStart:
case topLevelTypes.topDrop:
case topLevelTypes.topMouseDown:
case topLevelTypes.topMouseMove:
case topLevelTypes.topMouseUp:
EventConstructor = SyntheticMouseEvent;
break;
case topLevelTypes.topTouchCancel:
case topLevelTypes.topTouchEnd:
case topLevelTypes.topTouchMove:
case topLevelTypes.topTouchStart:
EventConstructor = SyntheticTouchEvent;
break;
case topLevelTypes.topScroll:
EventConstructor = SyntheticUIEvent;
break;
case topLevelTypes.topWheel:
EventConstructor = SyntheticWheelEvent;
break;
case topLevelTypes.topCopy:
case topLevelTypes.topCut:
case topLevelTypes.topPaste:
EventConstructor = SyntheticClipboardEvent;
break;
}
invariant(
EventConstructor,
'SimpleEventPlugin: Unhandled event type, `%s`.',
topLevelType
);
var event = EventConstructor.getPooled(
dispatchConfig,
topLevelTargetID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
};
module.exports = SimpleEventPlugin;
},{"./EventConstants":14,"./EventPropagators":19,"./SyntheticClipboardEvent":63,"./SyntheticEvent":65,"./SyntheticFocusEvent":66,"./SyntheticKeyboardEvent":67,"./SyntheticMouseEvent":68,"./SyntheticTouchEvent":69,"./SyntheticUIEvent":70,"./SyntheticWheelEvent":71,"./invariant":95,"./keyOf":102}],63:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticClipboardEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = require("./SyntheticEvent");
/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/
var ClipboardEventInterface = {
clipboardData: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
},{"./SyntheticEvent":65}],64:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticCompositionEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = require("./SyntheticEvent");
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/
var CompositionEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticCompositionEvent(
dispatchConfig,
dispatchMarker,
nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(
SyntheticCompositionEvent,
CompositionEventInterface
);
module.exports = SyntheticCompositionEvent;
},{"./SyntheticEvent":65}],65:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticEvent
* @typechecks static-only
*/
"use strict";
var PooledClass = require("./PooledClass");
var emptyFunction = require("./emptyFunction");
var getEventTarget = require("./getEventTarget");
var merge = require("./merge");
var mergeInto = require("./mergeInto");
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: getEventTarget,
currentTarget: null,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function(event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
*/
function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent) {
this.dispatchConfig = dispatchConfig;
this.dispatchMarker = dispatchMarker;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
this[propName] = nativeEvent[propName];
}
}
if (nativeEvent.defaultPrevented || nativeEvent.returnValue === false) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
}
mergeInto(SyntheticEvent.prototype, {
preventDefault: function() {
this.defaultPrevented = true;
var event = this.nativeEvent;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function() {
var event = this.nativeEvent;
event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function() {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function() {
var Interface = this.constructor.Interface;
for (var propName in Interface) {
this[propName] = null;
}
this.dispatchConfig = null;
this.dispatchMarker = null;
this.nativeEvent = null;
}
});
SyntheticEvent.Interface = EventInterface;
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function(Class, Interface) {
var Super = this;
var prototype = Object.create(Super.prototype);
mergeInto(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = merge(Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler);
module.exports = SyntheticEvent;
},{"./PooledClass":23,"./emptyFunction":81,"./getEventTarget":89,"./merge":104,"./mergeInto":106}],66:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticFocusEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = require("./SyntheticUIEvent");
/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var FocusEventInterface = {
relatedTarget: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
},{"./SyntheticUIEvent":70}],67:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticKeyboardEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = require("./SyntheticUIEvent");
/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var KeyboardEventInterface = {
'char': null,
key: null,
location: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
repeat: null,
locale: null,
// Legacy Interface
charCode: null,
keyCode: null,
which: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
},{"./SyntheticUIEvent":70}],68:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticMouseEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = require("./SyntheticUIEvent");
var ViewportMetrics = require("./ViewportMetrics");
/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var MouseEventInterface = {
screenX: null,
screenY: null,
clientX: null,
clientY: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
button: function(event) {
// Webkit, Firefox, IE9+
// which: 1 2 3
// button: 0 1 2 (standard)
var button = event.button;
if ('which' in event) {
return button;
}
// IE<9
// which: undefined
// button: 0 0 0
// button: 1 4 2 (onmouseup)
return button === 2 ? 2 : button === 4 ? 1 : 0;
},
buttons: null,
relatedTarget: function(event) {
return event.relatedTarget || (
event.fromElement === event.srcElement ?
event.toElement :
event.fromElement
);
},
// "Proprietary" Interface.
pageX: function(event) {
return 'pageX' in event ?
event.pageX :
event.clientX + ViewportMetrics.currentScrollLeft;
},
pageY: function(event) {
return 'pageY' in event ?
event.pageY :
event.clientY + ViewportMetrics.currentScrollTop;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
},{"./SyntheticUIEvent":70,"./ViewportMetrics":73}],69:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticTouchEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = require("./SyntheticUIEvent");
/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/
var TouchEventInterface = {
touches: null,
targetTouches: null,
changedTouches: null,
altKey: null,
metaKey: null,
ctrlKey: null,
shiftKey: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
},{"./SyntheticUIEvent":70}],70:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticUIEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = require("./SyntheticEvent");
/**
* @interface UIEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var UIEventInterface = {
view: null,
detail: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
},{"./SyntheticEvent":65}],71:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticWheelEvent
* @typechecks static-only
*/
"use strict";
var SyntheticMouseEvent = require("./SyntheticMouseEvent");
/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var WheelEventInterface = {
deltaX: function(event) {
// NOTE: IE<9 does not support x-axis delta.
return (
'deltaX' in event ? event.deltaX :
// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0
);
},
deltaY: function(event) {
return (
// Normalize (up is positive).
'deltaY' in event ? -event.deltaY :
// Fallback to `wheelDeltaY` for Webkit.
'wheelDeltaY' in event ? event.wheelDeltaY :
// Fallback to `wheelDelta` for IE<9.
'wheelDelta' in event ? event.wheelData : 0
);
},
deltaZ: null,
deltaMode: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticMouseEvent}
*/
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
},{"./SyntheticMouseEvent":68}],72:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule Transaction
*/
"use strict";
var invariant = require("./invariant");
/**
* `Transaction` creates a black box that is able to wrap any method such that
* certain invariants are maintained before and after the method is invoked
* (Even if an exception is thrown while invoking the wrapped method). Whoever
* instantiates a transaction can provide enforcers of the invariants at
* creation time. The `Transaction` class itself will supply one additional
* automatic invariant for you - the invariant that any transaction instance
* should not be ran while it is already being ran. You would typically create a
* single instance of a `Transaction` for reuse multiple times, that potentially
* is used to wrap several different methods. Wrappers are extremely simple -
* they only require implementing two methods.
*
* <pre>
* wrappers (injected at creation time)
* + +
* | |
* +-----------------|--------|--------------+
* | v | |
* | +---------------+ | |
* | +--| wrapper1 |---|----+ |
* | | +---------------+ v | |
* | | +-------------+ | |
* | | +----| wrapper2 |--------+ |
* | | | +-------------+ | | |
* | | | | | |
* | v v v v | wrapper
* | +---+ +---+ +---------+ +---+ +---+ | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +---+ +---+ +---------+ +---+ +---+ |
* | initialize close |
* +-----------------------------------------+
* </pre>
*
* Bonus:
* - Reports timing metrics by method name and wrapper index.
*
* Use cases:
* - Preserving the input selection ranges before/after reconciliation.
* Restoring selection even in the event of an unexpected error.
* - Deactivating events while rearranging the DOM, preventing blurs/focuses,
* while guaranteeing that afterwards, the event system is reactivated.
* - Flushing a queue of collected DOM mutations to the main UI thread after a
* reconciliation takes place in a worker thread.
* - Invoking any collected `componentDidRender` callbacks after rendering new
* content.
* - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
* to preserve the `scrollTop` (an automatic scroll aware DOM).
* - (Future use case): Layout calculations before and after DOM upates.
*
* Transactional plugin API:
* - A module that has an `initialize` method that returns any precomputation.
* - and a `close` method that accepts the precomputation. `close` is invoked
* when the wrapped process is completed, or has failed.
*
* @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules
* that implement `initialize` and `close`.
* @return {Transaction} Single transaction for reuse in thread.
*
* @class Transaction
*/
var Mixin = {
/**
* Sets up this instance so that it is prepared for collecting metrics. Does
* so such that this setup method may be used on an instance that is already
* initialized, in a way that does not consume additional memory upon reuse.
* That can be useful if you decide to make your subclass of this mixin a
* "PooledClass".
*/
reinitializeTransaction: function() {
this.transactionWrappers = this.getTransactionWrappers();
if (!this.wrapperInitData) {
this.wrapperInitData = [];
} else {
this.wrapperInitData.length = 0;
}
if (!this.timingMetrics) {
this.timingMetrics = {};
}
this.timingMetrics.methodInvocationTime = 0;
if (!this.timingMetrics.wrapperInitTimes) {
this.timingMetrics.wrapperInitTimes = [];
} else {
this.timingMetrics.wrapperInitTimes.length = 0;
}
if (!this.timingMetrics.wrapperCloseTimes) {
this.timingMetrics.wrapperCloseTimes = [];
} else {
this.timingMetrics.wrapperCloseTimes.length = 0;
}
this._isInTransaction = false;
},
_isInTransaction: false,
/**
* @abstract
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
*/
getTransactionWrappers: null,
isInTransaction: function() {
return !!this._isInTransaction;
},
/**
* Executes the function within a safety window. Use this for the top level
* methods that result in large amounts of computation/mutations that would
* need to be safety checked.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} args... Arguments to pass to the method (optional).
* Helps prevent need to bind in many cases.
* @return Return value from `method`.
*/
perform: function(method, scope, a, b, c, d, e, f) {
invariant(
!this.isInTransaction(),
'Transaction.perform(...): Cannot initialize a transaction when there ' +
'is already an outstanding transaction.'
);
var memberStart = Date.now();
var errorToThrow = null;
var ret;
try {
this.initializeAll();
ret = method.call(scope, a, b, c, d, e, f);
} catch (error) {
// IE8 requires `catch` in order to use `finally`.
errorToThrow = error;
} finally {
var memberEnd = Date.now();
this.methodInvocationTime += (memberEnd - memberStart);
try {
this.closeAll();
} catch (closeError) {
// If `method` throws, prefer to show that stack trace over any thrown
// by invoking `closeAll`.
errorToThrow = errorToThrow || closeError;
}
}
if (errorToThrow) {
throw errorToThrow;
}
return ret;
},
initializeAll: function() {
this._isInTransaction = true;
var transactionWrappers = this.transactionWrappers;
var wrapperInitTimes = this.timingMetrics.wrapperInitTimes;
var errorToThrow = null;
for (var i = 0; i < transactionWrappers.length; i++) {
var initStart = Date.now();
var wrapper = transactionWrappers[i];
try {
this.wrapperInitData[i] = wrapper.initialize ?
wrapper.initialize.call(this) :
null;
} catch (initError) {
// Prefer to show the stack trace of the first error.
errorToThrow = errorToThrow || initError;
this.wrapperInitData[i] = Transaction.OBSERVED_ERROR;
} finally {
var curInitTime = wrapperInitTimes[i];
var initEnd = Date.now();
wrapperInitTimes[i] = (curInitTime || 0) + (initEnd - initStart);
}
}
if (errorToThrow) {
throw errorToThrow;
}
},
/**
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
* them the respective return values of `this.transactionWrappers.init[i]`
* (`close`rs that correspond to initializers that failed will not be
* invoked).
*/
closeAll: function() {
invariant(
this.isInTransaction(),
'Transaction.closeAll(): Cannot close transaction when none are open.'
);
var transactionWrappers = this.transactionWrappers;
var wrapperCloseTimes = this.timingMetrics.wrapperCloseTimes;
var errorToThrow = null;
for (var i = 0; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
var closeStart = Date.now();
var initData = this.wrapperInitData[i];
try {
if (initData !== Transaction.OBSERVED_ERROR) {
wrapper.close && wrapper.close.call(this, initData);
}
} catch (closeError) {
// Prefer to show the stack trace of the first error.
errorToThrow = errorToThrow || closeError;
} finally {
var closeEnd = Date.now();
var curCloseTime = wrapperCloseTimes[i];
wrapperCloseTimes[i] = (curCloseTime || 0) + (closeEnd - closeStart);
}
}
this.wrapperInitData.length = 0;
this._isInTransaction = false;
if (errorToThrow) {
throw errorToThrow;
}
}
};
var Transaction = {
Mixin: Mixin,
/**
* Token to look for to determine if an error occured.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
},{"./invariant":95}],73:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ViewportMetrics
*/
"use strict";
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function() {
ViewportMetrics.currentScrollLeft =
document.body.scrollLeft + document.documentElement.scrollLeft;
ViewportMetrics.currentScrollTop =
document.body.scrollTop + document.documentElement.scrollTop;
}
};
module.exports = ViewportMetrics;
},{}],74:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule accumulate
*/
"use strict";
var invariant = require("./invariant");
/**
* Accumulates items that must not be null or undefined.
*
* This is used to conserve memory by avoiding array allocations.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulate(current, next) {
invariant(
next != null,
'accumulate(...): Accumulated items must be not be null or undefined.'
);
if (current == null) {
return next;
} else {
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
var currentIsArray = Array.isArray(current);
var nextIsArray = Array.isArray(next);
if (currentIsArray) {
return current.concat(next);
} else {
if (nextIsArray) {
return [current].concat(next);
} else {
return [current, next];
}
}
}
}
module.exports = accumulate;
},{"./invariant":95}],75:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule adler32
*/
/* jslint bitwise:true */
"use strict";
var MOD = 65521;
// This is a clean-room implementation of adler32 designed for detecting
// if markup is not what we expect it to be. It does not need to be
// cryptographically strong, only reasonable good at detecting if markup
// generated on the server is different than that on the client.
function adler32(data) {
var a = 1;
var b = 0;
for (var i = 0; i < data.length; i++) {
a = (a + data.charCodeAt(i)) % MOD;
b = (b + a) % MOD;
}
return a | (b << 16);
}
module.exports = adler32;
},{}],76:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule copyProperties
*/
/**
* Copy properties from one or more objects (up to 5) into the first object.
* This is a shallow copy. It mutates the first object and also returns it.
*
* NOTE: `arguments` has a very significant performance penalty, which is why
* we don't support unlimited arguments.
*/
function copyProperties(obj, a, b, c, d, e, f) {
obj = obj || {};
if (true) {
if (f) {
throw new Error('Too many arguments passed to copyProperties');
}
}
var args = [a, b, c, d, e];
var ii = 0, v;
while (args[ii]) {
v = args[ii++];
for (var k in v) {
obj[k] = v[k];
}
// IE ignores toString in object iteration.. See:
// webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html
if (v.hasOwnProperty && v.hasOwnProperty('toString') &&
(typeof v.toString != 'undefined') && (obj.toString !== v.toString)) {
obj.toString = v.toString;
}
}
return obj;
}
module.exports = copyProperties;
},{}],77:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule createArrayFrom
* @typechecks
*/
/**
* NOTE: if you are a previous user of this function, it has been considered
* unsafe because it's inconsistent across browsers for some inputs.
* Instead use `Array.isArray()`.
*
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
return (
// not null/false
!!obj &&
// arrays are objects, NodeLists are functions in Safari
(typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
('length' in obj) &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
(typeof obj.nodeType != 'number') &&
(
// a real array
(// HTMLCollection/NodeList
(Array.isArray(obj) ||
// arguments
('callee' in obj) || 'item' in obj))
)
);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFrom = require('createArrayFrom');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFrom(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* This is also good for converting certain pseudo-arrays, like `arguments` or
* HTMLCollections, into arrays.
*
* @param {*} obj
* @return {array}
*/
function createArrayFrom(obj) {
if (!hasArrayNature(obj)) {
return [obj];
}
if (obj.item) {
// IE does not support Array#slice on HTMLCollections
var l = obj.length, ret = new Array(l);
while (l--) { ret[l] = obj[l]; }
return ret;
}
return Array.prototype.slice.call(obj);
}
module.exports = createArrayFrom;
},{}],78:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule createNodesFromMarkup
* @typechecks
*/
/*jslint evil: true, sub: true */
var ExecutionEnvironment = require("./ExecutionEnvironment");
var createArrayFrom = require("./createArrayFrom");
var getMarkupWrap = require("./getMarkupWrap");
var invariant = require("./invariant");
/**
* Dummy container used to render all markup.
*/
var dummyNode =
ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Pattern used by `getNodeName`.
*/
var nodeNamePattern = /^\s*<(\w+)/;
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
* <script> element that is rendered. If no `handleScript` function is supplied,
* an exception is thrown if any <script> elements are rendered.
*
* @param {string} markup A string of valid HTML markup.
* @param {?function} handleScript Invoked once for each rendered <script>.
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
*/
function createNodesFromMarkup(markup, handleScript) {
var node = dummyNode;
invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized');
var nodeName = getNodeName(markup);
var wrap = nodeName && getMarkupWrap(nodeName);
if (wrap) {
node.innerHTML = wrap[1] + markup + wrap[2];
var wrapDepth = wrap[0];
while (wrapDepth--) {
node = node.lastChild;
}
} else {
node.innerHTML = markup;
}
var scripts = node.getElementsByTagName('script');
if (scripts.length) {
invariant(
handleScript,
'createNodesFromMarkup(...): Unexpected <script> element rendered.'
);
createArrayFrom(scripts).forEach(handleScript);
}
var nodes = createArrayFrom(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
},{"./ExecutionEnvironment":20,"./createArrayFrom":77,"./getMarkupWrap":90,"./invariant":95}],79:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule createObjectFrom
*/
/**
* Construct an object from an array of keys
* and optionally specified value or list of values.
*
* >>> createObjectFrom(['a','b','c']);
* {a: true, b: true, c: true}
*
* >>> createObjectFrom(['a','b','c'], false);
* {a: false, b: false, c: false}
*
* >>> createObjectFrom(['a','b','c'], 'monkey');
* {c:'monkey', b:'monkey' c:'monkey'}
*
* >>> createObjectFrom(['a','b','c'], [1,2,3]);
* {a: 1, b: 2, c: 3}
*
* >>> createObjectFrom(['women', 'men'], [true, false]);
* {women: true, men: false}
*
* @param Array list of keys
* @param mixed optional value or value array. defaults true.
* @returns object
*/
function createObjectFrom(keys, values /* = true */) {
if (true) {
if (!Array.isArray(keys)) {
throw new TypeError('Must pass an array of keys.');
}
}
var object = {};
var isArray = Array.isArray(values);
if (typeof values == 'undefined') {
values = true;
}
for (var ii = keys.length; ii--;) {
object[keys[ii]] = isArray ? values[ii] : values;
}
return object;
}
module.exports = createObjectFrom;
},{}],80:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule dangerousStyleValue
* @typechecks static-only
*/
"use strict";
var CSSProperty = require("./CSSProperty");
/**
* Convert a value into the proper css writable value. The `styleName` name
* name should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} styleName CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(styleName, value) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 || CSSProperty.isUnitlessNumber[styleName]) {
return '' + value; // cast to string
}
return value + 'px';
}
module.exports = dangerousStyleValue;
},{"./CSSProperty":2}],81:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule emptyFunction
*/
var copyProperties = require("./copyProperties");
function makeEmptyFunction(arg) {
return function() {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
function emptyFunction() {}
copyProperties(emptyFunction, {
thatReturns: makeEmptyFunction,
thatReturnsFalse: makeEmptyFunction(false),
thatReturnsTrue: makeEmptyFunction(true),
thatReturnsNull: makeEmptyFunction(null),
thatReturnsThis: function() { return this; },
thatReturnsArgument: function(arg) { return arg; }
});
module.exports = emptyFunction;
},{"./copyProperties":76}],82:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule escapeTextForBrowser
* @typechecks static-only
*/
"use strict";
var ESCAPE_LOOKUP = {
"&": "&",
">": ">",
"<": "<",
"\"": """,
"'": "'",
"/": "/"
};
var ESCAPE_REGEX = /[&><"'\/]/g;
function escaper(match) {
return ESCAPE_LOOKUP[match];
}
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextForBrowser(text) {
return ('' + text).replace(ESCAPE_REGEX, escaper);
}
module.exports = escapeTextForBrowser;
},{}],83:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ex
* @typechecks
* @nostacktrace
*/
/**
* This function transforms error message with arguments into plain text error
* message, so that it can be passed to window.onerror without losing anything.
* It can then be transformed back by `erx()` function.
*
* Usage:
* throw new Error(ex('Error %s from %s', errorCode, userID));
*
* @param {string} errorMessage
*/
var ex = function(errorMessage/*, arg1, arg2, ...*/) {
var args = Array.prototype.slice.call(arguments).map(function(arg) {
return String(arg);
});
var expectedLength = errorMessage.split('%s').length - 1;
if (expectedLength !== args.length - 1) {
// something wrong with the formatting string
return ex('ex args number mismatch: %s', JSON.stringify(args));
}
return ex._prefix + JSON.stringify(args) + ex._suffix;
};
ex._prefix = '<![EX[';
ex._suffix = ']]>';
module.exports = ex;
},{}],84:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule filterAttributes
* @typechecks static-only
*/
/*jslint evil: true */
'use strict';
/**
* Like filter(), but for a DOM nodes attributes. Returns an array of
* the filter DOMAttribute objects. Does some perf related this like
* caching attributes.length.
*
* @param {DOMElement} node Node whose attributes you want to filter
* @return {array} array of DOM attribute objects.
*/
function filterAttributes(node, func, context) {
var attributes = node.attributes;
var numAttributes = attributes.length;
var accumulator = [];
for (var i = 0; i < numAttributes; i++) {
var attr = attributes.item(i);
if (func.call(context, attr)) {
accumulator.push(attr);
}
}
return accumulator;
}
module.exports = filterAttributes;
},{}],85:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule flattenChildren
*/
"use strict";
var invariant = require("./invariant");
var traverseAllChildren = require("./traverseAllChildren");
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
*/
function flattenSingleChildIntoContext(traverseContext, child, name) {
// We found a component instance.
var result = traverseContext;
invariant(
!result.hasOwnProperty(name),
'flattenChildren(...): Encountered two children with the same key, `%s`. ' +
'Children keys must be unique.',
name
);
result[name] = child;
}
/**
* Flattens children that are typically specified as `props.children`.
* @return {!object} flattened children keyed by name.
*/
function flattenChildren(children) {
if (children == null) {
return children;
}
var result = {};
traverseAllChildren(children, flattenSingleChildIntoContext, result);
return result;
}
module.exports = flattenChildren;
},{"./invariant":95,"./traverseAllChildren":114}],86:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule forEachAccumulated
*/
"use strict";
/**
* @param {array} an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
*/
var forEachAccumulated = function(arr, cb, scope) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
};
module.exports = forEachAccumulated;
},{}],87:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ge
*/
/**
* Find a node by ID. Optionally search a sub-tree outside of the document
*
* Use ge if you're not sure whether or not the element exists. You can test
* for existence yourself in your application code.
*
* If your application code depends on the existence of the element, use $
* instead, which will throw in DEV if the element doesn't exist.
*/
function ge(arg, root, tag) {
return typeof arg != 'string' ? arg :
!root ? document.getElementById(arg) :
_geFromSubtree(arg, root, tag);
}
function _geFromSubtree(id, root, tag) {
var elem, children, ii;
if (_getNodeID(root) == id) {
return root;
} else if (root.getElementsByTagName) {
// All Elements implement this, which does an iterative DFS, which is
// faster than recursion and doesn't run into stack depth issues.
children = root.getElementsByTagName(tag || '*');
for (ii = 0; ii < children.length; ii++) {
if (_getNodeID(children[ii]) == id) {
return children[ii];
}
}
} else {
// DocumentFragment does not implement getElementsByTagName, so
// recurse over its children. Its children must be Elements, so
// each child will use the getElementsByTagName case instead.
children = root.childNodes;
for (ii = 0; ii < children.length; ii++) {
elem = _geFromSubtree(id, children[ii]);
if (elem) {
return elem;
}
}
}
return null;
}
/**
* Return the ID value for a given node. This allows us to avoid issues
* with forms that contain inputs with name="id".
*
* @return string (null if attribute not set)
*/
function _getNodeID(node) {
// #document and #document-fragment do not have getAttributeNode.
var id = node.getAttributeNode && node.getAttributeNode('id');
return id ? id.value : null;
}
module.exports = ge;
},{}],88:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getActiveElement
* @typechecks
*/
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*/
function getActiveElement() /*?DOMElement*/ {
try {
return document.activeElement;
} catch (e) {
return null;
}
}
module.exports = getActiveElement;
},{}],89:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getEventTarget
* @typechecks static-only
*/
"use strict";
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === 3 ? target.parentNode : target;
}
module.exports = getEventTarget;
},{}],90:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getMarkupWrap
*/
var ExecutionEnvironment = require("./ExecutionEnvironment");
var invariant = require("./invariant");
/**
* Dummy container used to detect which wraps are necessary.
*/
var dummyNode =
ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Some browsers cannot use `innerHTML` to render certain elements standalone,
* so we wrap them, render the wrapped nodes, then extract the desired node.
*
* In IE8, certain elements cannot render alone, so wrap all elements ('*').
*/
var shouldWrap = {
// Force wrapping for SVG elements because if they get created inside a <div>,
// they will be initialized in the wrong namespace (and will not display).
'circle': true,
'g': true,
'line': true,
'path': true,
'polyline': true,
'rect': true,
'text': true
};
var selectWrap = [1, '<select multiple="true">', '</select>'];
var tableWrap = [1, '<table>', '</table>'];
var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
var svgWrap = [1, '<svg>', '</svg>'];
var markupWrap = {
'*': [1, '?<div>', '</div>'],
'area': [1, '<map>', '</map>'],
'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
'legend': [1, '<fieldset>', '</fieldset>'],
'param': [1, '<object>', '</object>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'optgroup': selectWrap,
'option': selectWrap,
'caption': tableWrap,
'colgroup': tableWrap,
'tbody': tableWrap,
'tfoot': tableWrap,
'thead': tableWrap,
'td': trWrap,
'th': trWrap,
'circle': svgWrap,
'g': svgWrap,
'line': svgWrap,
'path': svgWrap,
'polyline': svgWrap,
'rect': svgWrap,
'text': svgWrap
};
/**
* Gets the markup wrap configuration for the supplied `nodeName`.
*
* NOTE: This lazily detects which wraps are necessary for the current browser.
*
* @param {string} nodeName Lowercase `nodeName`.
* @return {?array} Markup wrap configuration, if applicable.
*/
function getMarkupWrap(nodeName) {
invariant(!!dummyNode, 'Markup wrapping node not initialized');
if (!markupWrap.hasOwnProperty(nodeName)) {
nodeName = '*';
}
if (!shouldWrap.hasOwnProperty(nodeName)) {
if (nodeName === '*') {
dummyNode.innerHTML = '<link />';
} else {
dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>';
}
shouldWrap[nodeName] = !dummyNode.firstChild;
}
return shouldWrap[nodeName] ? markupWrap[nodeName] : null;
}
module.exports = getMarkupWrap;
},{"./ExecutionEnvironment":20,"./invariant":95}],91:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getNodeForCharacterOffset
*/
"use strict";
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType == 3) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
module.exports = getNodeForCharacterOffset;
},{}],92:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getReactRootElementInContainer
*/
"use strict";
var DOC_NODE_TYPE = 9;
/**
* @param {DOMElement|DOMDocument} container DOM element that may contain
* a React component
* @return {?*} DOM element that may have the reactRoot ID, or null.
*/
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOC_NODE_TYPE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
module.exports = getReactRootElementInContainer;
},{}],93:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getTextContentAccessor
*/
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
var contentKey = null;
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) {
contentKey = 'innerText' in document.createElement('div') ?
'innerText' :
'textContent';
}
return contentKey;
}
module.exports = getTextContentAccessor;
},{"./ExecutionEnvironment":20}],94:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule hyphenate
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
},{}],95:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule invariant
*/
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf style format 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.
*/
function invariant(condition) {
if (!condition) {
throw new Error('Invariant Violation');
}
}
module.exports = invariant;
if (true) {
var invariantDev = function(condition, format, a, b, c, d, e, f) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
if (!condition) {
var args = [a, b, c, d, e, f];
var argIndex = 0;
throw new Error(
'Invariant Violation: ' +
format.replace(/%s/g, function() { return args[argIndex++]; })
);
}
};
module.exports = invariantDev;
}
},{}],96:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule isEventSupported
*/
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
var testNode, useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
testNode = document.createElement('div');
useHasFeature =
document.implementation &&
document.implementation.hasFeature &&
// `hasFeature` always returns true in Firefox 19+.
document.implementation.hasFeature('', '') !== true;
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!testNode || (capture && !testNode.addEventListener)) {
return false;
}
var element = document.createElement('div');
var eventName = 'on' + eventNameSuffix;
var isSupported = eventName in element;
if (!isSupported) {
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
if (typeof element[eventName] !== 'undefined') {
element[eventName] = undefined;
}
element.removeAttribute(eventName);
}
if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
// This is the only way to test support for the `wheel` event in IE9+.
isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
}
element = null;
return isSupported;
}
module.exports = isEventSupported;
},{"./ExecutionEnvironment":20}],97:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule isNode
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
function isNode(object) {
return !!(object && (
typeof Node !== 'undefined' ? object instanceof Node :
typeof object === 'object' &&
typeof object.nodeType === 'number' &&
typeof object.nodeName === 'string'
));
}
module.exports = isNode;
},{}],98:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule isTextInputElement
*/
"use strict";
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
var supportedInputTypes = {
'color': true,
'date': true,
'datetime': true,
'datetime-local': true,
'email': true,
'month': true,
'number': true,
'password': true,
'range': true,
'search': true,
'tel': true,
'text': true,
'time': true,
'url': true,
'week': true
};
function isTextInputElement(elem) {
return elem && (
(elem.nodeName === 'INPUT' && supportedInputTypes[elem.type]) ||
elem.nodeName === 'TEXTAREA'
);
}
module.exports = isTextInputElement;
},{}],99:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule isTextNode
* @typechecks
*/
var isNode = require("./isNode");
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM text node.
*/
function isTextNode(object) {
return isNode(object) && object.nodeType == 3;
}
module.exports = isTextNode;
},{"./isNode":97}],100:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule joinClasses
* @typechecks static-only
*/
"use strict";
/**
* Combines multiple className strings into one.
* http://jsperf.com/joinclasses-args-vs-array
*
* @param {...?string} classes
* @return {string}
*/
function joinClasses(className/*, ... */) {
if (!className) {
className = '';
}
var nextClass;
var argLength = arguments.length;
if (argLength > 1) {
for (var ii = 1; ii < argLength; ii++) {
nextClass = arguments[ii];
nextClass && (className += ' ' + nextClass);
}
}
return className;
}
module.exports = joinClasses;
},{}],101:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule keyMirror
* @typechecks static-only
*/
"use strict";
var invariant = require("./invariant");
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function(obj) {
var ret = {};
var key;
invariant(
obj instanceof Object && !Array.isArray(obj),
'keyMirror(...): Argument must be an object.'
);
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
},{"./invariant":95}],102:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule keyOf
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without loosing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
var keyOf = function(oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
},{}],103:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule memoizeStringOnly
* @typechecks static-only
*/
"use strict";
/**
* Memoizes the return value of a function that accepts one string argument.
*
* @param {function} callback
* @return {function}
*/
function memoizeStringOnly(callback) {
var cache = {};
return function(string) {
if (cache.hasOwnProperty(string)) {
return cache[string];
} else {
return cache[string] = callback.call(this, string);
}
};
}
module.exports = memoizeStringOnly;
},{}],104:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule merge
*/
"use strict";
var mergeInto = require("./mergeInto");
/**
* Shallow merges two structures into a return value, without mutating either.
*
* @param {?object} one Optional object with properties to merge from.
* @param {?object} two Optional object with properties to merge from.
* @return {object} The shallow extension of one by two.
*/
var merge = function(one, two) {
var result = {};
mergeInto(result, one);
mergeInto(result, two);
return result;
};
module.exports = merge;
},{"./mergeInto":106}],105:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule mergeHelpers
*
* requiresPolyfills: Array.isArray
*/
"use strict";
var invariant = require("./invariant");
var keyMirror = require("./keyMirror");
/**
* Maximum number of levels to traverse. Will catch circular structures.
* @const
*/
var MAX_MERGE_DEPTH = 36;
/**
* We won't worry about edge cases like new String('x') or new Boolean(true).
* Functions are considered terminals, and arrays are not.
* @param {*} o The item/object/value to test.
* @return {boolean} true iff the argument is a terminal.
*/
var isTerminal = function(o) {
return typeof o !== 'object' || o === null;
};
var mergeHelpers = {
MAX_MERGE_DEPTH: MAX_MERGE_DEPTH,
isTerminal: isTerminal,
/**
* Converts null/undefined values into empty object.
*
* @param {?Object=} arg Argument to be normalized (nullable optional)
* @return {!Object}
*/
normalizeMergeArg: function(arg) {
return arg === undefined || arg === null ? {} : arg;
},
/**
* If merging Arrays, a merge strategy *must* be supplied. If not, it is
* likely the caller's fault. If this function is ever called with anything
* but `one` and `two` being `Array`s, it is the fault of the merge utilities.
*
* @param {*} one Array to merge into.
* @param {*} two Array to merge from.
*/
checkMergeArrayArgs: function(one, two) {
invariant(
Array.isArray(one) && Array.isArray(two),
'Critical assumptions about the merge functions have been violated. ' +
'This is the fault of the merge functions themselves, not necessarily ' +
'the callers.'
);
},
/**
* @param {*} one Object to merge into.
* @param {*} two Object to merge from.
*/
checkMergeObjectArgs: function(one, two) {
mergeHelpers.checkMergeObjectArg(one);
mergeHelpers.checkMergeObjectArg(two);
},
/**
* @param {*} arg
*/
checkMergeObjectArg: function(arg) {
invariant(
!isTerminal(arg) && !Array.isArray(arg),
'Critical assumptions about the merge functions have been violated. ' +
'This is the fault of the merge functions themselves, not necessarily ' +
'the callers.'
);
},
/**
* Checks that a merge was not given a circular object or an object that had
* too great of depth.
*
* @param {number} Level of recursion to validate against maximum.
*/
checkMergeLevel: function(level) {
invariant(
level < MAX_MERGE_DEPTH,
'Maximum deep merge depth exceeded. You may be attempting to merge ' +
'circular structures in an unsupported way.'
);
},
/**
* Checks that the supplied merge strategy is valid.
*
* @param {string} Array merge strategy.
*/
checkArrayStrategy: function(strategy) {
invariant(
strategy === undefined || strategy in mergeHelpers.ArrayStrategies,
'You must provide an array strategy to deep merge functions to ' +
'instruct the deep merge how to resolve merging two arrays.'
);
},
/**
* Set of possible behaviors of merge algorithms when encountering two Arrays
* that must be merged together.
* - `clobber`: The left `Array` is ignored.
* - `indexByIndex`: The result is achieved by recursively deep merging at
* each index. (not yet supported.)
*/
ArrayStrategies: keyMirror({
Clobber: true,
IndexByIndex: true
})
};
module.exports = mergeHelpers;
},{"./invariant":95,"./keyMirror":101}],106:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule mergeInto
* @typechecks static-only
*/
"use strict";
var mergeHelpers = require("./mergeHelpers");
var checkMergeObjectArg = mergeHelpers.checkMergeObjectArg;
/**
* Shallow merges two structures by mutating the first parameter.
*
* @param {object} one Object to be merged into.
* @param {?object} two Optional object with properties to merge from.
*/
function mergeInto(one, two) {
checkMergeObjectArg(one);
if (two != null) {
checkMergeObjectArg(two);
for (var key in two) {
if (!two.hasOwnProperty(key)) {
continue;
}
one[key] = two[key];
}
}
}
module.exports = mergeInto;
},{"./mergeHelpers":105}],107:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule mixInto
*/
"use strict";
/**
* Simply copies properties to the prototype.
*/
var mixInto = function(constructor, methodBag) {
var methodName;
for (methodName in methodBag) {
if (!methodBag.hasOwnProperty(methodName)) {
continue;
}
constructor.prototype[methodName] = methodBag[methodName];
}
};
module.exports = mixInto;
},{}],108:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule mutateHTMLNodeWithMarkup
* @typechecks static-only
*/
/*jslint evil: true */
'use strict';
var createNodesFromMarkup = require("./createNodesFromMarkup");
var filterAttributes = require("./filterAttributes");
var invariant = require("./invariant");
/**
* You can't set the innerHTML of a document. Unless you have
* this function.
*
* @param {DOMElement} node with tagName == 'html'
* @param {string} markup markup string including <html>.
*/
function mutateHTMLNodeWithMarkup(node, markup) {
invariant(
node.tagName.toLowerCase() === 'html',
'mutateHTMLNodeWithMarkup(): node must have tagName of "html", got %s',
node.tagName
);
markup = markup.trim();
invariant(
markup.toLowerCase().indexOf('<html') === 0,
'mutateHTMLNodeWithMarkup(): markup must start with <html'
);
// First let's extract the various pieces of markup.
var htmlOpenTagEnd = markup.indexOf('>') + 1;
var htmlCloseTagStart = markup.lastIndexOf('<');
var htmlOpenTag = markup.substring(0, htmlOpenTagEnd);
var innerHTML = markup.substring(htmlOpenTagEnd, htmlCloseTagStart);
// Now for the fun stuff. Pass through both sets of attributes and
// bring them up-to-date. We get the new set by creating a markup
// fragment.
var shouldExtractAttributes = htmlOpenTag.indexOf(' ') > -1;
var attributeHolder = null;
if (shouldExtractAttributes) {
// We extract the attributes by creating a <span> and evaluating
// the node.
attributeHolder = createNodesFromMarkup(
htmlOpenTag.replace('html ', 'span ') + '</span>'
)[0];
// Add all attributes present in attributeHolder
var attributesToSet = filterAttributes(
attributeHolder,
function(attr) {
return node.getAttributeNS(attr.namespaceURI, attr.name) !== attr.value;
}
);
attributesToSet.forEach(function(attr) {
node.setAttributeNS(attr.namespaceURI, attr.name, attr.value);
});
}
// Remove all attributes not present in attributeHolder
var attributesToRemove = filterAttributes(
node,
function(attr) {
// Remove all attributes if attributeHolder is null or if it does not have
// the desired attribute.
return !(
attributeHolder &&
attributeHolder.hasAttributeNS(attr.namespaceURI, attr.name)
);
}
);
attributesToRemove.forEach(function(attr) {
node.removeAttributeNS(attr.namespaceURI, attr.name);
});
// Finally, set the inner HTML. No tricks needed. Do this last to
// minimize likelihood of triggering reflows.
node.innerHTML = innerHTML;
}
module.exports = mutateHTMLNodeWithMarkup;
},{"./createNodesFromMarkup":78,"./filterAttributes":84,"./invariant":95}],109:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule nodeContains
* @typechecks
*/
var isTextNode = require("./isTextNode");
/*jslint bitwise:true */
/**
* Checks if a given DOM node contains or is another DOM node.
*
* @param {?DOMNode} outerNode Outer DOM node.
* @param {?DOMNode} innerNode Inner DOM node.
* @return {boolean} True if `outerNode` contains or is `innerNode`.
*/
function nodeContains(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return nodeContains(outerNode, innerNode.parentNode);
} else if (outerNode.contains) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
module.exports = nodeContains;
},{"./isTextNode":99}],110:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule objMap
*/
"use strict";
/**
* For each key/value pair, invokes callback func and constructs a resulting
* object which contains, for every key in obj, values that are the result of
* of invoking the function:
*
* func(value, key, iteration)
*
* @param {?object} obj Object to map keys over
* @param {function} func Invoked for each key/val pair.
* @param {?*} context
* @return {?object} Result of mapping or null if obj is falsey
*/
function objMap(obj, func, context) {
if (!obj) {
return null;
}
var i = 0;
var ret = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = func.call(context, obj[key], key, i++);
}
}
return ret;
}
module.exports = objMap;
},{}],111:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule objMapKeyVal
*/
"use strict";
/**
* Behaves the same as `objMap` but invokes func with the key first, and value
* second. Use `objMap` unless you need this special case.
* Invokes func as:
*
* func(key, value, iteration)
*
* @param {?object} obj Object to map keys over
* @param {!function} func Invoked for each key/val pair.
* @param {?*} context
* @return {?object} Result of mapping or null if obj is falsey
*/
function objMapKeyVal(obj, func, context) {
if (!obj) {
return null;
}
var i = 0;
var ret = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = func.call(context, key, obj[key], i++);
}
}
return ret;
}
module.exports = objMapKeyVal;
},{}],112:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule performanceNow
* @typechecks static-only
*/
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
/**
* Detect if we can use window.performance.now() and gracefully
* fallback to Date.now() if it doesn't exist.
* We need to support Firefox < 15 for now due to Facebook's webdriver
* infrastructure.
*/
var performance = null;
if (ExecutionEnvironment.canUseDOM) {
performance = window.performance || window.webkitPerformance;
}
if (!performance || !performance.now) {
performance = Date;
}
var performanceNow = performance.now.bind(performance);
module.exports = performanceNow;
},{"./ExecutionEnvironment":20}],113:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule shallowEqual
*/
"use strict";
/**
* Performs equality by iterating through keys on an object and returning
* false when any key has values which are not strictly equal between
* objA and objB. Returns true when the values of all keys are strictly equal.
*
* @return {boolean}
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var key;
// Test for A's keys different from B.
for (key in objA) {
if (objA.hasOwnProperty(key) &&
(!objB.hasOwnProperty(key) || objA[key] !== objB[key])) {
return false;
}
}
// Test for B'a keys missing from A.
for (key in objB) {
if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
},{}],114:[function(require,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule traverseAllChildren
*/
"use strict";
var ReactComponent = require("./ReactComponent");
var ReactTextComponent = require("./ReactTextComponent");
var invariant = require("./invariant");
/**
* TODO: Test that:
* 1. `mapChildren` transforms strings and numbers into `ReactTextComponent`.
* 2. it('should fail when supplied duplicate key', function() {
* 3. That a single child and an array with one item have the same key pattern.
* });
*/
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!number} indexSoFar Number of children encountered until this point.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
var traverseAllChildrenImpl =
function(children, nameSoFar, indexSoFar, callback, traverseContext) {
var subtreeCount = 0; // Count of children found in the current subtree.
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var child = children[i];
var nextName = nameSoFar + ReactComponent.getKey(child, i);
var nextIndex = indexSoFar + subtreeCount;
subtreeCount += traverseAllChildrenImpl(
child,
nextName,
nextIndex,
callback,
traverseContext
);
}
} else {
var type = typeof children;
var isOnlyChild = nameSoFar === '';
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows
var storageName = isOnlyChild ?
ReactComponent.getKey(children, 0):
nameSoFar;
if (children === null || children === undefined || type === 'boolean') {
// All of the above are perceived as null.
callback(traverseContext, null, storageName, indexSoFar);
subtreeCount = 1;
} else if (children.mountComponentIntoNode) {
callback(traverseContext, children, storageName, indexSoFar);
subtreeCount = 1;
} else {
if (type === 'object') {
invariant(
!children || children.nodeType !== 1,
'traverseAllChildren(...): Encountered an invalid child; DOM ' +
'elements are not valid children of React components.'
);
for (var key in children) {
if (children.hasOwnProperty(key)) {
subtreeCount += traverseAllChildrenImpl(
children[key],
nameSoFar + '{' + key + '}',
indexSoFar + subtreeCount,
callback,
traverseContext
);
}
}
} else if (type === 'string') {
var normalizedText = new ReactTextComponent(children);
callback(traverseContext, normalizedText, storageName, indexSoFar);
subtreeCount += 1;
} else if (type === 'number') {
var normalizedNumber = new ReactTextComponent('' + children);
callback(traverseContext, normalizedNumber, storageName, indexSoFar);
subtreeCount += 1;
}
}
}
return subtreeCount;
};
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children !== null && children !== undefined) {
traverseAllChildrenImpl(children, '', 0, callback, traverseContext);
}
}
module.exports = traverseAllChildren;
},{"./ReactComponent":25,"./ReactTextComponent":59,"./invariant":95}]},{},[24])
(24)
});
; |
editor/src/Onboarding/index.js | jddeeds/jddeeds.github.io | import React from 'react'
import styled from 'styled-components'
import Transition from 'react-motion-ui-pack'
import Button from '../Button'
const Container = styled.div`
padding: 10px;
position: absolute;
background-color: whitesmoke;
left: 5vw;
top: 5vh;
overflow-y: auto;
height: 90vh;
width: 90vw;
div {
padding-bottom: 10px;
}
`
const InnerContainer = styled.div`
margin: 0 auto;
max-width: 640px;
`
const Title = styled.h1`
margin-top: 0;
padding-top: 18px;
font-size: 56px;
font-weight: 300;
`
const Sub = styled.h1`
font-size: 16px;
font-weight: normal;
margin-top: 0;
`
const FAQ = styled.div`
h1 {
font-weight: 300;
}
li, div {
padding-bottom: 10px;
}
div {
padding-left: 10px;
}
`
export default ({ onStart, show }) => (
<Transition
component={false}
enter={{ opacity: 1, scale: 1 }}
leave={{ opacity: 0, scale: 1.3 }}
>
{ show &&
<Container key='container'>
<InnerContainer>
<Title centered>Riyu Editor</Title>
<Sub centered><b>
<a href='https://github.com/Secretmapper/Riyu'>Riyu</a>
</b> is a cool, modern, and minimal portfolio/personal web page template that is super easy to customize.</Sub>
<Sub><b>Riyu Editor</b> is a companion web app that allows you to <i>easily</i> add your own content for Riyu. The editor creates both a ready built html file you can drop on your server and a data.json file for use on Riyu's build system.</Sub>
<FAQ>
<h1>FAQ:</h1>
<ul>
<li>How do I add my own images for my projects?</li>
<div>Simply add in the expected filename of your image (project.png) and generate the HTML. Then place your images on a directory named img - this is where all the images are resolved (/img/project.png). You can of course edit the html once generated.</div>
<li>Can I change the colour scheme?</li>
<div>You can change the colour scheme (and every style really) of Riyu. Changing colour schemes/styles through the Riyu Editor web app is currently not supported.</div>
<li>Is it free?</li>
<div>Riyu is free (as in beer) and open source (MIT). There is no need to add credits or linkbacks, but I'd appreciate if you star the <a href='https://github.com/Secretmapper/Riyu'>repo</a> :)</div>
</ul>
</FAQ>
<div>I'd love to hear what everyone is doing with Riyu. If so inclined, Open an <a href='https://github.com/Secretmapper/Riyu/issues'>issue here</a> with a link to a site built on Riyu</div>
<div>You can open this page again by clicking the i button on the left inside the editor</div>
<Button onClick={onStart}>Start Editing</Button>
</InnerContainer>
</Container>
}
</Transition>
)
|
packages/material-ui-icons/src/AttachMoneyTwoTone.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M11.5 17.1c-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c1.95-.37 3.5-1.5 3.5-3.55 0-2.84-2.43-3.81-4.7-4.4-2.27-.59-3-1.2-3-2.15 0-1.09 1.01-1.85 2.7-1.85 1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-1.94.42-3.5 1.68-3.5 3.61 0 2.31 1.91 3.46 4.7 4.13 2.5.6 3 1.48 3 2.41 0 .69-.49 1.79-2.7 1.79z" />
, 'AttachMoneyTwoTone');
|
ajax/libs/vue-material/1.0.0-beta-7/components/MdTable/index.js | wout/cdnjs | !(function(e,t){var n,r;if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("vue"));else if("function"==typeof define&&define.amd)define(["vue"],t);else{n=t("object"==typeof exports?require("vue"):e.Vue);for(r in n)("object"==typeof exports?exports:e)[r]=n[r]}})(this,(function(e){return (function(e){function t(r){if(n[r])return n[r].exports;var a=n[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,t),a.l=!0,a.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=428)})({0:function(e,t){e.exports=function(e,t,n,r,a,i){var l,o,s,d,u,c=e=e||{},f=typeof e.default;return"object"!==f&&"function"!==f||(l=e,c=e.default),o="function"==typeof c?c.options:c,t&&(o.render=t.render,o.staticRenderFns=t.staticRenderFns,o._compiled=!0),n&&(o.functional=!0),a&&(o._scopeId=a),i?(s=function(e){e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,e||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),r&&r.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(i)},o._ssrRegister=s):r&&(s=r),s&&(d=o.functional,u=d?o.render:o.beforeCreate,d?(o._injectStyles=s,o.render=function(e,t){return s.call(t),u(e,t)}):o.beforeCreate=u?[].concat(u,s):[s]),{esModule:l,exports:c,options:o}}},1:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var a,i,l,o;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t={props:{mdTheme:null},computed:{$mdActiveTheme:function(){var e=i.default.enabled,t=i.default.getThemeName,n=i.default.getAncestorTheme;return e&&!1!==this.mdTheme?t(this.mdTheme||n(this)):null}}};return(0,o.default)(t,e)},a=n(4),i=r(a),l=n(6),o=r(l)},109:function(e,t,n){"use strict";function r(e){n(358)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(359),i=n.n(a),l=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("tr",{staticClass:"md-table-row",class:e.rowClasses,on:{click:e.onClick}},[e.selectableCount?n("md-table-cell-selection",{attrs:{"md-disabled":e.mdDisabled,"md-selectable":"multiple"===e.mdSelectable,"md-row-id":e.mdIndex},model:{value:e.isSelected,callback:function(t){e.isSelected=t},expression:"isSelected"}}):e._e(),e._v(" "),e._t("default")],2)},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},11:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){return Math.random().toString(36).slice(4)};t.default=r},110:function(e,t,n){"use strict";function r(e){n(360)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(361),i=n.n(a),l=function(){var e=this,t=e.$createElement,n=e._self._c||t;return e.mdSelectable?n("td",{staticClass:"md-table-cell md-table-cell-selection"},[n("div",{staticClass:"md-table-cell-container"},[n("md-checkbox",{attrs:{disabled:!e.mdSelectable||e.mdDisabled},on:{change:e.onChange},model:{value:e.isSelected,callback:function(t){e.isSelected=t},expression:"isSelected"}})],1)]):e._e()},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},111:function(e,t){},112:function(e,t,n){"use strict";var r,a;Object.defineProperty(t,"__esModule",{value:!0}),r=n(1),a=(function(e){return e&&e.__esModule?e:{default:e}})(r),t.default=new a.default({name:"MdToolbar",props:{mdElevation:{type:[String,Number],default:4}}})},12:function(e,t,n){(function(t){var r,a,i,l,o,s=n(15),d="undefined"==typeof window?t:window,u=["moz","webkit"],c="AnimationFrame",f=d["request"+c],m=d["cancel"+c]||d["cancelRequest"+c];for(r=0;!f&&r<u.length;r++)f=d[u[r]+"Request"+c],m=d[u[r]+"Cancel"+c]||d[u[r]+"CancelRequest"+c];f&&m||(a=0,i=0,l=[],o=1e3/60,f=function(e){if(0===l.length){var t=s(),n=Math.max(0,o-(t-a));a=n+t,setTimeout((function(){var e,t=l.slice(0);for(l.length=0,e=0;e<t.length;e++)if(!t[e].cancelled)try{t[e].callback(a)}catch(e){setTimeout((function(){throw e}),0)}}),Math.round(n))}return l.push({handle:++i,callback:e,cancelled:!1}),i},m=function(e){for(var t=0;t<l.length;t++)l[t].handle===e&&(l[t].cancelled=!0)}),e.exports=function(e){return f.call(d,e)},e.exports.cancel=function(){m.apply(d,arguments)},e.exports.polyfill=function(e){e||(e=d),e.requestAnimationFrame=f,e.cancelAnimationFrame=m}}).call(t,n(13))},13:function(e,t){var n;n=(function(){return this})();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},15:function(e,t,n){(function(t){(function(){var n,r,a,i,l,o;"undefined"!=typeof performance&&null!==performance&&performance.now?e.exports=function(){return performance.now()}:void 0!==t&&null!==t&&t.hrtime?(e.exports=function(){return(n()-l)/1e6},r=t.hrtime,n=function(){var e;return e=r(),1e9*e[0]+e[1]},i=n(),o=1e9*t.uptime(),l=i-o):Date.now?(e.exports=function(){return Date.now()-a},a=Date.now()):(e.exports=function(){return(new Date).getTime()-a},a=(new Date).getTime())}).call(this)}).call(t,n(16))},16:function(e,t){function n(){throw Error("setTimeout has not been defined")}function r(){throw Error("clearTimeout has not been defined")}function a(e){if(u===setTimeout)return setTimeout(e,0);if((u===n||!u)&&setTimeout)return u=setTimeout,setTimeout(e,0);try{return u(e,0)}catch(t){try{return u.call(null,e,0)}catch(t){return u.call(this,e,0)}}}function i(e){if(c===clearTimeout)return clearTimeout(e);if((c===r||!c)&&clearTimeout)return c=clearTimeout,clearTimeout(e);try{return c(e)}catch(t){try{return c.call(null,e)}catch(t){return c.call(this,e)}}}function l(){m&&h&&(m=!1,h.length?f=h.concat(f):p=-1,f.length&&o())}function o(){var e,t;if(!m){for(e=a(l),m=!0,t=f.length;t;){for(h=f,f=[];++p<t;)h&&h[p].run();p=-1,t=f.length}h=null,m=!1,i(e)}}function s(e,t){this.fun=e,this.array=t}function d(){}var u,c,f,m,h,p,b=e.exports={};!(function(){try{u="function"==typeof setTimeout?setTimeout:n}catch(e){u=n}try{c="function"==typeof clearTimeout?clearTimeout:r}catch(e){c=r}})(),f=[],m=!1,p=-1,b.nextTick=function(e){var t,n=Array(arguments.length-1);if(arguments.length>1)for(t=1;t<arguments.length;t++)n[t-1]=arguments[t];f.push(new s(e,n)),1!==f.length||m||a(o)},s.prototype.run=function(){this.fun.apply(null,this.array)},b.title="browser",b.browser=!0,b.env={},b.argv=[],b.version="",b.versions={},b.on=d,b.addListener=d,b.once=d,b.off=d,b.removeListener=d,b.removeAllListeners=d,b.emit=d,b.prependListener=d,b.prependOnceListener=d,b.listeners=function(e){return[]},b.binding=function(e){throw Error("process.binding is not supported")},b.cwd=function(){return"/"},b.chdir=function(e){throw Error("process.chdir is not supported")},b.umask=function(){return 0}},2:function(t,n){t.exports=e},21:function(e,t){},22:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var a,i,l,o;Object.defineProperty(t,"__esModule",{value:!0}),a=n(1),i=r(a),l=n(23),o=r(l),t.default=new i.default({name:"MdIcon",components:{MdSvgLoader:o.default},props:{mdSrc:String}})},23:function(e,t,n){"use strict";function r(e){n(24)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(25),i=n.n(a),l=function(){var e=this,t=e.$createElement;return(e._self._c||t)("i",{staticClass:"md-svg-loader",domProps:{innerHTML:e._s(e.html)}})},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},24:function(e,t){},25:function(e,t,n){"use strict";function r(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,n){function r(a,i){var l,o;try{l=t[a](i),o=l.value}catch(e){return void n(e)}if(!l.done)return Promise.resolve(o).then((function(e){r("next",e)}),(function(e){r("throw",e)}));e(o)}return r("next")})}}Object.defineProperty(t,"__esModule",{value:!0});var a={};t.default={name:"MdSVGLoader",props:{mdSrc:{type:String,required:!0}},data:function(){return{html:null,error:null}},watch:{mdSrc:function(){this.html=null,this.loadSVG()}},methods:{isSVG:function(e){return e.indexOf("svg")>=0},setHtml:(function(){function e(e){return t.apply(this,arguments)}var t=r(regeneratorRuntime.mark((function e(t){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,a[this.mdSrc];case 2:return this.html=e.sent,e.next=5,this.$nextTick();case 5:this.$emit("md-loaded");case 6:case"end":return e.stop()}}),e,this)})));return e})(),unexpectedError:function(e){this.error="Something bad happened trying to fetch "+this.mdSrc+".",e(this.error)},loadSVG:function(){var e=this;a.hasOwnProperty(this.mdSrc)?this.setHtml():a[this.mdSrc]=new Promise(function(t,n){var r=new window.XMLHttpRequest;r.open("GET",e.mdSrc,!0),r.onload=function(){var a=r.getResponseHeader("content-type");200===r.status?e.isSVG(a)?(t(r.response),e.setHtml()):(e.error="The file "+e.mdSrc+" is not a valid SVG.",n(e.error)):r.status>=400&&r.status<500?(e.error="The file "+e.mdSrc+" do not exists.",n(e.error)):e.unexpectedError(n)},r.onerror=function(){return e.unexpectedError(n)},r.onabort=function(){return e.unexpectedError(n)},r.send()})}},mounted:function(){this.loadSVG()}}},3:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var a,i,l,o,s;Object.defineProperty(t,"__esModule",{value:!0}),n(7),a=n(5),i=r(a),l=n(4),o=r(l),s=function(){var e=new i.default({ripple:!0,theming:{},locale:{startYear:1900,endYear:2099,dateFormat:"YYYY-MM-DD",days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shorterDays:["S","M","T","W","T","F","S"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"],shorterMonths:["J","F","M","A","M","Ju","Ju","A","Se","O","N","D"]}});return Object.defineProperties(e.theming,{metaColors:{get:function(){return o.default.metaColors},set:function(e){o.default.metaColors=e}},theme:{get:function(){return o.default.theme},set:function(e){o.default.theme=e}},enabled:{get:function(){return o.default.enabled},set:function(e){o.default.enabled=e}}}),e},t.default=function(e){e.material||(e.material=s(),e.prototype.$material=e.material)}},31:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={methods:{isAssetIcon:function(e){return/\w+[\/\\.]\w+/.test(e)}}}},340:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var a,i,l,o,s,d,u,c,f,m,h,p,b,v,_,S;Object.defineProperty(t,"__esModule",{value:!0}),a=n(3),i=r(a),l=n(341),o=r(l),s=n(364),d=r(s),u=n(367),c=r(u),f=n(109),m=r(f),h=n(67),p=r(h),b=n(370),v=r(b),_=n(373),S=r(_),t.default=function(e){(0,i.default)(e),e.component("MdTable",o.default),e.component(d.default.name,d.default),e.component(c.default.name,c.default),e.component(m.default.name,m.default),e.component(p.default.name,p.default),e.component(v.default.name,v.default),e.component(S.default.name,S.default)}},341:function(e,t,n){"use strict";function r(e,t){var n=["md-table-toolbar","md-table-empty-state","md-table-pagination"],r=Array.from(e),a={};return r.forEach((function(e,t){if(e&&e.tag){var i=e.componentOptions&&e.componentOptions.tag;i&&n.includes(i)&&(e.data.slot=i,e.data.attrs=e.data.attrs||{},a[i]=function(){return e},r.splice(t,1))}})),{childNodes:r,slots:a}}var a,i,l;Object.defineProperty(t,"__esModule",{value:!0}),a=Object.assign||function(e){var t,n,r;for(t=1;t<arguments.length;t++){n=arguments[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(342),l=(function(e){return e&&e.__esModule?e:{default:e}})(i),t.default={name:"MdTableContainer",functional:!0,render:function(e,t){var n,i,o,s=t.data,d=t.props,u=t.children,c=[],f=s.scopedSlots;return u&&(n=r(u,e),i=n.childNodes,o=n.slots,c=i,f=a({},f,o)),e(l.default,a({},s,{props:d,scopedSlots:f}),[c])}}},342:function(e,t,n){"use strict";function r(e){n(343)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(344),i=n.n(a),l=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("md-tag-switcher",{staticClass:"md-table",attrs:{"md-tag":e.contentTag}},[e._t("md-table-toolbar"),e._v(" "),n("keep-alive",[e.$scopedSlots["md-table-alternate-header"]&&e.selectedCount?n("md-table-alternate-header",[e._t("md-table-alternate-header",null,{count:e.selectedCount})],2):e._e()],1),e._v(" "),e.mdFixedHeader?n("div",{staticClass:"md-table-fixed-header",class:e.headerClasses,style:e.headerStyles},[n("table",[n("md-table-thead")],1)]):e._e(),e._v(" "),n("md-content",{staticClass:"md-table-content md-scrollbar",class:e.contentClasses,style:e.contentStyles,on:{scroll:e.setScroll}},[n("table",[!e.mdFixedHeader&&e.$scopedSlots["md-table-row"]?n("md-table-thead",{class:e.headerClasses}):e._e(),e._v(" "),e.$scopedSlots["md-table-row"]?e.value.length?n("tbody",e._l(e.value,(function(t,r){return n("md-table-row-ghost",{key:e.getRowId(t[e.mdModelId]),attrs:{"md-id":e.getRowId(t[e.mdModelId]),"md-index":r}},[e._t("md-table-row",null,{item:t})],2)}))):e.$scopedSlots["md-table-empty-state"]?n("tbody",[n("tr",[n("td",{attrs:{colspan:e.headerCount}},[e._t("md-table-empty-state")],2)])]):e._e():n("tbody",[e._t("default")],2)],1),e._v(" "),e._t("md-table-pagination")],2),e._v(" "),e.value?e._t("default"):e._e()],2)},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},343:function(e,t){},344:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var a,i,l,o,s,d,u,c,f,m,h,p,b,v,_,S,g,y,M;Object.defineProperty(t,"__esModule",{value:!0}),a=Object.assign||function(e){var t,n,r;for(t=1;t<arguments.length;t++){n=arguments[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(12),l=r(i),o=n(345),s=r(o),d=n(11),u=r(d),c=n(8),f=r(c),m=n(347),h=r(m),p=n(355),b=r(p),v=n(109),_=r(v),S=n(362),g=r(S),y=n(110),M=r(y),t.default={name:"MdTable",components:{MdTagSwitcher:s.default,MdTableAlternateHeader:b.default,MdTableThead:h.default,MdTableRow:_.default,MdTableRowGhost:g.default,MdTableCellSelection:M.default},props:{value:[Array,Object],mdModelId:{type:String,default:"id"},mdCard:Boolean,mdFixedHeader:Boolean,mdHeight:{type:Number,default:400},mdSort:String,mdSortOrder:a({type:String,default:"asc"},(0,f.default)("md-sort-order",["asc","desc"])),mdSortFn:{type:Function,default:function(e){var t=this;return e.sort((function(e,n){var r=t.MdTable.sort;return"desc"===t.MdTable.sortOrder?e[r].localeCompare(n[r]):n[r].localeCompare(e[r])}))}}},data:function(){return{fixedHeaderPadding:0,hasContentScroll:!1,MdTable:{items:{},sort:null,sortOrder:null,singleSelection:null,selectedItems:{},selectable:{},fixedHeader:null,contentPadding:null,contentEl:null,hasValue:this.hasValue,emitEvent:this.emitEvent,sortTable:this.sortTable,manageItemSelection:this.manageItemSelection,getModel:this.getModel,getModelItem:this.getModelItem}}},computed:{contentTag:function(){return this.mdCard?"md-card":"md-content"},headerCount:function(){return Object.keys(this.MdTable.items).length},selectedCount:function(){return Object.keys(this.MdTable.selectedItems).length},headerStyles:function(){if(this.mdFixedHeader)return"padding-right: "+this.fixedHeaderPadding+"px"},hasValue:function(){return this.value&&0!==this.value.length},headerClasses:function(){if(this.mdFixedHeader&&this.hasContentScroll||!this.hasValue)return"md-table-fixed-header-active"},contentStyles:function(){if(this.mdFixedHeader)return"height: "+this.mdHeight+"px"},contentClasses:function(){if(this.mdFixedHeader&&0===this.value.length)return"md-table-empty"}},provide:function(){return{MdTable:this.MdTable}},watch:{mdSort:{immediate:!0,handler:function(){this.MdTable.sort=this.mdSort}},mdSortOrder:{immediate:!0,handler:function(){this.MdTable.sortOrder=this.mdSortOrder}},mdFixedHeader:{immediate:!0,handler:function(){this.MdTable.fixedHeader=this.mdFixedHeader}},hasValue:{immediate:!0,handler:function(){this.MdTable.hasValue=this.hasValue}}},methods:{emitEvent:function(e,t){this.$emit(e,t)},getRowId:function(e){return e||"md-row-"+(0,u.default)()},setScroll:function(e){var t=this;(0,l.default)((function(){t.hasContentScroll=e.target.scrollTop>0}))},getContentEl:function(){return this.$el.querySelector(".md-table-content")},setContentEl:function(){this.MdTable.contentEl=this.getContentEl()},setHeaderPadding:function(){var e,t;this.setContentEl(),e=this.MdTable.contentEl,t=e.childNodes[0],this.fixedHeaderPadding=e.offsetWidth-t.offsetWidth},getModel:function(){return this.value},getModelItem:function(e){return this.value[e]},manageItemSelection:function(e){this.MdTable.selectedItems[e]?this.$delete(this.MdTable.selectedItems,e):this.$set(this.MdTable.selectedItems,e,this.value[e]),this.sendSelectionEvent()},sendSelectionEvent:function(){this.$emit("md-selected",Object.values(this.MdTable.selectedItems))},sortTable:function(){Array.isArray(this.value)&&this.$emit("input",this.mdSortFn(this.value))}},mounted:function(){this.setContentEl(),this.mdFixedHeader&&this.setHeaderPadding()}}},345:function(e,t,n){"use strict";var r,a,i,l,o,s,d,u,c;Object.defineProperty(t,"__esModule",{value:!0}),r=n(346),a=n.n(r),i=n(0),l=null,o=!1,s=null,d=null,u=null,c=i(a.a,l,o,s,d,u),t.default=c.exports},346:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){var t,n,r;for(t=1;t<arguments.length;t++){n=arguments[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.default={functional:!0,props:{mdTag:{type:String,default:"div"}},render:function(e,t){var n=t.props,a=t.children,i=t.data,l=t.listeners;return e(n.mdTag,r({},i,{on:l}),a)}}},347:function(e,t,n){"use strict";var r,a,i,l,o,s,d,u,c,f,m,h;Object.defineProperty(t,"__esModule",{value:!0}),r=n(348),a=n.n(r),i=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("thead",[n("tr",[n("md-table-head-selection"),e._v(" "),e._l(e.MdTable.items,(function(t,r){return n("md-table-head",e._b({key:r},"md-table-head",t,!1))}))],2)])},l=[],o={render:i,staticRenderFns:l},s=o,d=n(0),u=!1,c=null,f=null,m=null,h=d(a.a,s,u,c,f,m),t.default=h.exports},348:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var a,i,l,o;Object.defineProperty(t,"__esModule",{value:!0}),a=n(67),i=r(a),l=n(353),o=r(l),t.default={name:"MdTableThead",inject:["MdTable"],components:{MdTableHead:i.default,MdTableHeadSelection:o.default}}},349:function(e,t){},350:function(e,t,n){"use strict";function r(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,n){function r(a,i){var l,o;try{l=t[a](i),o=l.value}catch(e){return void n(e)}if(!l.done)return Promise.resolve(o).then((function(e){r("next",e)}),(function(e){r("throw",e)}));e(o)}return r("next")})}}var a,i;Object.defineProperty(t,"__esModule",{value:!0}),a=n(351),i=(function(e){return e&&e.__esModule?e:{default:e}})(a),t.default={name:"MdTableHead",components:{MdUpwardIcon:i.default},props:{mdNumeric:Boolean,numeric:Boolean,label:String,tooltip:String,sortBy:String},inject:["MdTable"],data:function(){return{width:null}},computed:{hasSort:function(){return this.MdTable.sort&&this.sortBy},isSorted:function(){if(this.MdTable.sort)return this.MdTable.sort===this.sortBy},isDescSorted:function(){return this.isSorted&&"desc"===this.MdTable.sortOrder},isAscSorted:function(){return this.isSorted&&"asc"===this.MdTable.sortOrder},headStyles:function(){return{width:this.width+"px"}},headClasses:function(){return{"md-numeric":this.numeric||this.mdNumeric,"md-sortable":this.hasSort,"md-sorted":this.isSorted,"md-sorted-desc":this.isDescSorted}}},methods:{changeSort:function(){this.hasSort&&(this.isAscSorted?this.MdTable.sortOrder="desc":this.MdTable.sortOrder="asc",this.MdTable.sort=this.sortBy,this.MdTable.emitEvent("md-sorted",this.MdTable.sort),this.MdTable.emitEvent("update:mdSort",this.MdTable.sort),this.MdTable.emitEvent("update:mdSortOrder",this.MdTable.sortOrder),this.MdTable.sortTable())},getChildNodesBySelector:function(e,t){return Array.from(e.childNodes).filter((function(e){var n=e.classList;return n&&n.contains(t)}))},getNodeIndex:function(e,t){return[].indexOf.call(e,t)},setWidth:function(){var e,t,n,r;this.MdTable.fixedHeader&&(e="md-table-cell",t=this.getChildNodesBySelector(this.$el.parentNode,"md-table-head"),n=this.MdTable.contentEl.querySelectorAll("tr:first-child ."+e),r=this.getNodeIndex(t,this.$el),this.width=n[r].offsetWidth)}},updated:(function(){function e(){return t.apply(this,arguments)}var t=r(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.$nextTick();case 2:this.setWidth();case 3:case"end":return e.stop()}}),e,this)})));return e})(),mounted:(function(){function e(){return t.apply(this,arguments)}var t=r(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.$nextTick();case 2:this.setWidth();case 3:case"end":return e.stop()}}),e,this)})));return e})()}},351:function(e,t,n){"use strict";var r,a,i,l,o,s,d,u,c,f,m,h;Object.defineProperty(t,"__esModule",{value:!0}),r=n(352),a=n.n(r),i=function(){var e=this,t=e.$createElement;e._self._c;return e._m(0)},l=[function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("md-icon",{staticClass:"md-icon-image"},[n("svg",{attrs:{height:"24",viewBox:"0 0 24 24",width:"24",xmlns:"http://www.w3.org/2000/svg"}},[n("path",{attrs:{d:"M0 0h24v24H0V0z",fill:"none"}}),e._v(" "),n("path",{attrs:{d:"M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8-8 8z"}})])])}],o={render:i,staticRenderFns:l},s=o,d=n(0),u=!1,c=null,f=null,m=null,h=d(a.a,s,u,c,f,m),t.default=h.exports},352:function(e,t,n){"use strict";var r,a;Object.defineProperty(t,"__esModule",{value:!0}),r=n(9),a=(function(e){return e&&e.__esModule?e:{default:e}})(r),t.default={name:"MdArrowDownIcon",components:{MdIcon:a.default}}},353:function(e,t,n){"use strict";var r,a,i,l,o,s,d,u,c,f,m,h;Object.defineProperty(t,"__esModule",{value:!0}),r=n(354),a=n.n(r),i=function(){var e=this,t=e.$createElement,n=e._self._c||t;return e.selectableCount?n("md-table-head",{staticClass:"md-table-cell-selection"},[n("div",{staticClass:"md-table-cell-container"},[n("md-checkbox",{attrs:{disabled:e.isDisabled},on:{change:e.onChange},model:{value:e.allSelected,callback:function(t){e.allSelected=t},expression:"allSelected"}})],1)]):e._e()},l=[],o={render:i,staticRenderFns:l},s=o,d=n(0),u=!1,c=null,f=null,m=null,h=d(a.a,s,u,c,f,m),t.default=h.exports},354:function(e,t,n){"use strict";var r,a;Object.defineProperty(t,"__esModule",{value:!0}),r=n(67),a=(function(e){return e&&e.__esModule?e:{default:e}})(r),t.default={name:"MdTableHeadSelection",components:{MdTableHead:a.default},inject:["MdTable"],data:function(){return{allSelected:!1}},computed:{selectableCount:function(){return Object.keys(this.selectable).length},isDisabled:function(){return!this.selectableCount},selectable:function(){return this.MdTable.selectable},selectedItems:function(){return this.MdTable.selectedItems}},watch:{selectedItems:{immediate:!0,deep:!0,handler:function(e){var t=this;window.setTimeout((function(){var n=Object.keys(e).length;t.selectableCount>0&&n>0&&(t.allSelected=n===t.selectableCount)}),10)}}},methods:{onChange:function(){var e=this;Object.values(this.MdTable.selectable).forEach((function(t){t(e.allSelected)}))}}}},355:function(e,t,n){"use strict";function r(e){n(356)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(357),i=n.n(a),l=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("transition",{attrs:{name:"md-table-alternate-header"}},[n("div",{staticClass:"md-table-alternate-header"},[e._t("default")],2)])},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},356:function(e,t){},357:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"MdTableAlternateHeader"}},358:function(e,t){},359:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var a,i,l,o,s;Object.defineProperty(t,"__esModule",{value:!0}),a=Object.assign||function(e){var t,n,r;for(t=1;t<arguments.length;t++){n=arguments[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(8),l=r(i),o=n(110),s=r(o),t.default={name:"MdTableRow",components:{MdTableCellSelection:s.default},props:{mdIndex:[Number,String],mdId:[Number,String],mdSelectable:a({type:[String]},(0,l.default)("md-selectable",["multiple","single"])),mdDisabled:Boolean,mdAutoSelect:Boolean},inject:["MdTable"],data:function(){return{index:null,isSelected:!1}},computed:{selectableCount:function(){return Object.keys(this.MdTable.selectable).length},isSingleSelected:function(){return this.MdTable.singleSelection===this.mdId},hasMultipleSelection:function(){return this.MdTable.hasValue&&"multiple"===this.mdSelectable},hasSingleSelection:function(){return this.MdTable.hasValue&&"single"===this.mdSelectable},rowClasses:function(){if(this.MdTable.hasValue)return{"md-has-selection":!this.mdDisabled&&(this.mdAutoSelect||this.hasSingleSelection),"md-selected":this.isSelected,"md-selected-single":this.isSingleSelected}}},watch:{mdDisabled:function(){this.mdDisabled?this.removeSelectableItem():this.addSelectableItem()},mdId:function(e,t){this.removeSelectableItem(t),this.addSelectableItem(e)},isSelected:function(){this.MdTable.manageItemSelection(this.mdIndex)}},methods:{onClick:function(){this.MdTable.hasValue&&!this.mdDisabled&&(this.hasMultipleSelection?this.selectRowIfMultiple():this.hasSingleSelection&&this.selectRowIfSingle())},toggleSelection:function(){this.isSelected=!this.isSelected},selectRowIfSingle:function(){this.MdTable.singleSelection===this.mdId?(this.MdTable.singleSelection=null,this.$emit("md-selected",null)):(this.MdTable.singleSelection=this.mdId,this.$emit("md-selected",this.MdTable.getModelItem(this.mdIndex)))},selectRowIfMultiple:function(){this.mdAutoSelect&&this.toggleSelection()},addSelectableItem:function(e){var t=this;this.hasMultipleSelection&&!this.mdDisabled&&this.$set(this.MdTable.selectable,e||this.mdId,(function(e){t.isSelected=e}))},removeSelectableItem:function(e){this.hasMultipleSelection&&this.$delete(this.MdTable.selectable,e||this.mdId)}},created:function(){this.addSelectableItem()},beforeDestroy:function(){this.removeSelectableItem()}}},360:function(e,t){},361:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"MdTableCellSelection",props:{value:Boolean,mdRowId:[Number,String],mdSelectable:Boolean,mdDisabled:Boolean},inject:["MdTable"],data:function(){return{isSelected:!1}},watch:{value:function(){this.isSelected=this.value}},methods:{onChange:function(){this.$emit("input",this.isSelected)}}}},362:function(e,t,n){"use strict";var r,a,i,l,o,s,d,u,c;Object.defineProperty(t,"__esModule",{value:!0}),r=n(363),a=n.n(r),i=n(0),l=null,o=!1,s=null,d=null,u=null,c=i(a.a,l,o,s,d,u),t.default=c.exports},363:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"MdTableRowGhost",abstract:!0,props:{mdIndex:[String,Number],mdId:[String,Number]},render:function(){return this.$slots.default[0].componentOptions.propsData.mdIndex=this.mdIndex,this.$slots.default[0].componentOptions.propsData.mdId=this.mdId,this.$slots.default[0]}}},364:function(e,t,n){"use strict";function r(e){n(365)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(366),i=n.n(a),l=function(){var e=this,t=e.$createElement;return(e._self._c||t)("md-toolbar",{staticClass:"md-table-toolbar md-transparent",attrs:{"md-elevation":0}},[e._t("default")],2)},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},365:function(e,t){},366:function(e,t,n){"use strict";var r,a;Object.defineProperty(t,"__esModule",{value:!0}),r=n(75),a=(function(e){return e&&e.__esModule?e:{default:e}})(r),t.default={name:"MdTableToolbar",components:{MdToolbar:a.default},inject:["MdTable"]}},367:function(e,t,n){"use strict";function r(e){n(368)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(369),i=n.n(a),l=function(){var e=this,t=e.$createElement;return(e._self._c||t)("md-empty-state",e._b({staticClass:"md-table-empty-state"},"md-empty-state",e.$props,!1),[e._t("default")],2)},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},368:function(e,t){},369:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var a,i,l;Object.defineProperty(t,"__esModule",{value:!0}),a=n(70),r(a),i=n(63),l=r(i),t.default={name:"MdTableEmptyState",props:l.default,inject:["MdTable"]}},370:function(e,t,n){"use strict";function r(e){n(371)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(372),i=n.n(a),l=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("td",{staticClass:"md-table-cell",class:e.cellClasses},[n("div",{staticClass:"md-table-cell-container"},[e._t("default")],2)])},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},371:function(e,t){},372:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"MdTableCell",props:{mdLabel:String,mdNumeric:Boolean,mdTooltip:String,mdSortBy:String},inject:["MdTable"],data:function(){return{index:null}},computed:{cellClasses:function(){return{"md-numeric":this.mdNumeric}}},watch:{mdSortBy:function(){this.setCellData()},mdNumeric:function(){this.setCellData()},mdLabel:function(){this.setCellData()},mdTooltip:function(){this.setCellData()}},methods:{setCellData:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this;this.$set(this.MdTable.items,e.index,{label:e.mdLabel,numeric:e.mdNumeric,tooltip:e.mdTooltip,sortBy:e.mdSortBy})},updateAllCellData:function(){var e=this;Array.from(this.$el.parentNode.childNodes).filter((function(e){var t=e.tagName,n=e.classList,r=n&&n.contains("md-table-cell-selection");return t&&"td"===t.toLowerCase()&&!r})).forEach((function(t,n){var r=t.__vue__;r.index=n,e.setCellData(r)}))}},mounted:function(){this.updateAllCellData()}}},373:function(e,t,n){"use strict";function r(e){n(374)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(375),i=n.n(a),l=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"md-table-pagination"},[!1!==e.mdPageOptions?[n("span",{staticClass:"md-table-pagination-label"},[e._v(e._s(e.mdLabel))]),e._v(" "),n("md-field",[n("md-select",{attrs:{"md-dense":"","md-class":"md-pagination-select"},on:{changed:e.setPageSize},model:{value:e.currentPageSize,callback:function(t){e.currentPageSize=t},expression:"currentPageSize"}},e._l(e.mdPageOptions,(function(t){return n("md-option",{key:t,attrs:{value:t}},[e._v(e._s(t))])})))],1)]:e._e(),e._v(" "),n("span",[e._v(e._s(e.currentItemCount)+"-"+e._s(e.currentPageCount)+" "+e._s(e.mdSeparator)+" "+e._s(e.mdTotal))]),e._v(" "),n("md-button",{staticClass:"md-icon-button md-table-pagination-previous",attrs:{disabled:1===e.mdPage},on:{click:function(t){e.goToPrevious()}}},[n("md-icon",[e._v("keyboard_arrow_left")])],1),e._v(" "),n("md-button",{staticClass:"md-icon-button md-table-pagination-next",on:{click:function(t){e.goToNext()}}},[n("md-icon",[e._v("keyboard_arrow_right")])],1)],2)},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},374:function(e,t){},375:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"MdTablePagination",inject:["MdTable"],props:{mdPageSize:{type:[String,Number],default:10},mdPageOptions:{type:Array,default:function(){return[10,25,50,100]}},mdPage:{type:Number,default:1},mdTotal:{type:[String,Number],default:"Many"},mdLabel:{type:String,default:"Rows per page:"},mdSeparator:{type:String,default:"of"}},data:function(){return{currentPageSize:0}},computed:{currentItemCount:function(){return(this.mdPage-1)*this.mdPageSize+1},currentPageCount:function(){return this.mdPage*this.mdPageSize}},watch:{mdPageSize:{immediate:!0,handler:function(e){this.currentPageSize=this.pageSize}}},methods:{setPageSize:function(){this.$emit("update:mdPageSize",this.currentPageSize)},goToPrevious:function(){},goToNext:function(){}},created:function(){this.currentPageSize=this.mdPageSize}}},4:function(e,t,n){"use strict";var r,a,i,l,o;Object.defineProperty(t,"__esModule",{value:!0}),r=n(2),a=(function(e){return e&&e.__esModule?e:{default:e}})(r),i=null,l=null,o=null,t.default=new a.default({data:function(){return{prefix:"md-theme-",theme:"default",enabled:!0,metaColors:!1}},computed:{themeTarget:function(){return!this.$isServer&&document.documentElement},fullThemeName:function(){return this.getThemeName()}},watch:{enabled:{immediate:!0,handler:function(){var e=this.fullThemeName,t=this.themeTarget,n=this.enabled;t&&(n?(t.classList.add(e),this.metaColors&&this.setHtmlMetaColors(e)):(t.classList.remove(e),this.metaColors&&this.setHtmlMetaColors()))}},theme:function(e,t){var n=this.getThemeName,r=this.themeTarget;e=n(e),r.classList.remove(n(t)),r.classList.add(e),this.metaColors&&this.setHtmlMetaColors(e)},metaColors:function(e){e?this.setHtmlMetaColors(this.fullThemeName):this.setHtmlMetaColors()}},methods:{getAncestorTheme:function(e){var t,n=this;return e?(t=e.mdTheme,(function e(r){if(r){var a=r.mdTheme,i=r.$parent;return a&&a!==t?a:e(i)}return n.theme})(e.$parent)):null},getThemeName:function(e){var t=e||this.theme;return this.prefix+t},setMicrosoftColors:function(e){i&&i.setAttribute("content",e)},setThemeColors:function(e){l&&l.setAttribute("content",e)},setMaskColors:function(e){o&&o.setAttribute("color",e)},setHtmlMetaColors:function(e){var t,n="#fff";e&&(t=window.getComputedStyle(document.documentElement),n=t.getPropertyValue("--"+e+"-primary")),n&&(this.setMicrosoftColors(n),this.setThemeColors(n),this.setMaskColors(n))}},mounted:function(){var e=this;i=document.querySelector('[name="msapplication-TileColor"]'),l=document.querySelector('[name="theme-color"]'),o=document.querySelector('[rel="mask-icon"]'),this.enabled&&this.metaColors&&window.addEventListener("load",(function(){e.setHtmlMetaColors(e.fullThemeName)}))}})},428:function(e,t,n){e.exports=n(340)},5:function(e,t,n){"use strict";var r,a;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t={};return a.default.util.defineReactive(t,"reactive",e),t.reactive},r=n(2),a=(function(e){return e&&e.__esModule?e:{default:e}})(r)},6:function(e,t,n){"use strict";function r(e){return!!e&&"object"==typeof e}function a(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||i(e)}function i(e){return e.$$typeof===m}function l(e){return Array.isArray(e)?[]:{}}function o(e,t){return t&&!1===t.clone||!c(e)?e:u(l(e),e,t)}function s(e,t,n){return e.concat(t).map((function(e){return o(e,n)}))}function d(e,t,n){var r={};return c(e)&&Object.keys(e).forEach((function(t){r[t]=o(e[t],n)})),Object.keys(t).forEach((function(a){c(t[a])&&e[a]?r[a]=u(e[a],t[a],n):r[a]=o(t[a],n)})),r}function u(e,t,n){var r=Array.isArray(t),a=Array.isArray(e),i=n||{arrayMerge:s};return r===a?r?(i.arrayMerge||s)(e,t,n):d(e,t,n):o(t,n)}var c,f,m,h;Object.defineProperty(t,"__esModule",{value:!0}),c=function(e){return r(e)&&!a(e)},f="function"==typeof Symbol&&Symbol.for,m=f?Symbol.for("react.element"):60103,u.all=function(e,t){if(!Array.isArray(e))throw Error("first argument should be an array");return e.reduce((function(e,n){return u(e,n,t)}),{})},h=u,t.default=h},63:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={mdRounded:Boolean,mdSize:{type:Number,default:420},mdIcon:String,mdLabel:String,mdDescription:String}},67:function(e,t,n){"use strict";function r(e){n(349)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(350),i=n.n(a),l=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("th",{staticClass:"md-table-head",class:e.headClasses,style:e.headStyles,on:{click:e.changeSort}},[e.$slots.default?n("div",{staticClass:"md-table-head-container"},[n("div",{staticClass:"md-table-head-label"},[e._t("default")],2)]):n("md-ripple",{staticClass:"md-table-head-container",attrs:{"md-disabled":!e.hasSort}},[n("div",{staticClass:"md-table-head-label"},[e.hasSort?n("md-upward-icon",{staticClass:"md-table-sortable-icon"},[e._v("arrow_upward")]):e._e(),e._v("\n\n "+e._s(e.label)+"\n\n "),e.tooltip?n("md-tooltip",[e._v(e._s(e.tooltip))]):e._e()],1)])],1)},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},7:function(e,t){},70:function(e,t,n){"use strict";function r(e){n(84)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(85),i=n.n(a),l=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("transition",{attrs:{name:"md-empty-state",appear:""}},[n("div",{staticClass:"md-empty-state",class:[e.emptyStateClasses,e.$mdActiveTheme],style:e.emptyStateStyles},[n("div",{staticClass:"md-empty-state-container"},[e.mdIcon?[e.isAssetIcon(e.mdIcon)?n("md-icon",{staticClass:"md-empty-state-icon",attrs:{"md-src":e.mdIcon}}):n("md-icon",{staticClass:"md-empty-state-icon"},[e._v(e._s(e.mdIcon))])]:e._e(),e._v(" "),e.mdLabel?n("strong",{staticClass:"md-empty-state-label"},[e._v(e._s(e.mdLabel))]):e._e(),e._v(" "),e.mdDescription?n("p",{staticClass:"md-empty-state-description"},[e._v(e._s(e.mdDescription))]):e._e(),e._v(" "),e._t("default")],2)])])},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},75:function(e,t,n){"use strict";function r(e){n(111)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(112),i=n.n(a),l=function(){var e=this,t=e.$createElement;return(e._self._c||t)("div",{staticClass:"md-toolbar",class:[e.$mdActiveTheme,"md-elevation-"+e.mdElevation]},[e._t("default")],2)},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports},8:function(e,t,n){"use strict";var r,a;Object.defineProperty(t,"__esModule",{value:!0}),r=n(2),a=(function(e){return e&&e.__esModule?e:{default:e}})(r),t.default=function(e,t){return{validator:function(n){return!!t.includes(n)||(a.default.util.warn("The "+e+" prop is invalid. Given value: "+n+". Available options: "+t.join(", ")+".",void 0),!1)}}}},84:function(e,t){},85:function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var a,i,l,o,s,d;Object.defineProperty(t,"__esModule",{value:!0}),a=n(1),i=r(a),l=n(63),o=r(l),s=n(31),d=r(s),t.default=new i.default({name:"MdEmptyState",mixins:[d.default],props:o.default,computed:{emptyStateClasses:function(){return{"md-rounded":this.mdRounded}},emptyStateStyles:function(){if(this.mdRounded){var e=this.mdSize+"px";return{width:e,height:e}}}}})},9:function(e,t,n){"use strict";function r(e){n(21)}var a,i,l,o,s,d,u,c,f,m,h,p;Object.defineProperty(t,"__esModule",{value:!0}),a=n(22),i=n.n(a),l=function(){var e=this,t=e.$createElement,n=e._self._c||t;return e.mdSrc?n("md-svg-loader",{staticClass:"md-icon md-icon-image",class:[e.$mdActiveTheme],attrs:{"md-src":e.mdSrc},on:{"md-loaded":function(t){e.$emit("md-loaded")}}}):n("i",{staticClass:"md-icon md-icon-font",class:[e.$mdActiveTheme]},[e._t("default")],2)},o=[],s={render:l,staticRenderFns:o},d=s,u=n(0),c=!1,f=r,m=null,h=null,p=u(i.a,d,c,f,m,h),t.default=p.exports}})})); |
src/components/login/LoginPage.js | TulevaEE/onboarding-client | import React from 'react';
import { PropTypes as Types } from 'prop-types';
import { Redirect, withRouter } from 'react-router-dom';
import { FacebookProvider, Like } from 'react-facebook';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import './LoginPage.scss';
import { logo, AuthenticationLoader, ErrorAlert } from '../common';
import LoginForm from './loginForm';
import {
changePhoneNumber,
changePersonalCode,
authenticateWithMobileId,
cancelMobileAuthentication,
authenticateWithIdCard,
authenticateWithIdCode,
} from './actions';
export const LoginPage = ({
isAuthenticated,
onMobileIdSubmit,
onPhoneNumberChange,
onPersonalCodeChange,
onCancelMobileAuthentication,
onIdCodeSubmit,
onAuthenticateWithIdCard,
phoneNumber,
personalCode,
controlCode,
loadingAuthentication,
loadingUserConversion,
errorDescription,
monthlyThirdPillarContribution,
exchangeExistingThirdPillarUnits,
location,
}) =>
isAuthenticated ? (
<Redirect to={location.state && location.state.from ? location.state.from : ''} />
) : (
<div className="login-page">
<div className="container pt-5">
<div className="row">
<div className="col-lg-12 text-center">
<img src={logo} alt="Tuleva" className="img-responsive brand-logo mb-3 pb-3 mt-2" />
</div>
</div>
<div className="row">
<div className="col-lg-10 offset-lg-1 col-sm-12 offset-sm-0 text-center">
<div className="col-lg-6 offset-lg-3 col-md-8 offset-md-2 col-sm-12">
{errorDescription ? <ErrorAlert description={errorDescription} /> : ''}
{!loadingAuthentication && !controlCode && !loadingUserConversion ? (
<LoginForm
onMobileIdSubmit={onMobileIdSubmit}
onPhoneNumberChange={onPhoneNumberChange}
onPersonalCodeChange={onPersonalCodeChange}
phoneNumber={phoneNumber}
personalCode={personalCode}
onIdCodeSubmit={onIdCodeSubmit}
onAuthenticateWithIdCard={onAuthenticateWithIdCard}
monthlyThirdPillarContribution={monthlyThirdPillarContribution}
exchangeExistingThirdPillarUnits={exchangeExistingThirdPillarUnits}
/>
) : (
''
)}
{!errorDescription &&
(loadingAuthentication || controlCode || loadingUserConversion) ? (
<AuthenticationLoader
onCancel={onCancelMobileAuthentication}
controlCode={controlCode}
/>
) : (
''
)}
</div>
<div className="col-lg-6 offset-lg-3 col-md-8 offset-md-2 col-sm-12 fb-widget mt-3">
<FacebookProvider appId="1939240566313354">
<Like href="https://www.facebook.com/Tuleva.ee" showFaces />
</FacebookProvider>
</div>
</div>
</div>
</div>
</div>
);
const noop = () => null;
export const loginPath = '/login';
LoginPage.defaultProps = {
onPhoneNumberChange: noop,
onPersonalCodeChange: noop,
onMobileIdSubmit: noop,
onCancelMobileAuthentication: noop,
onIdCodeSubmit: noop,
onAuthenticateWithIdCard: noop,
isAuthenticated: false,
phoneNumber: '',
personalCode: '',
controlCode: '',
loadingAuthentication: false,
loadingUserConversion: false,
errorDescription: '',
monthlyThirdPillarContribution: null,
exchangeExistingThirdPillarUnits: false,
location: { state: { from: '' } },
};
LoginPage.propTypes = {
onPhoneNumberChange: Types.func,
onPersonalCodeChange: Types.func,
onMobileIdSubmit: Types.func,
onCancelMobileAuthentication: Types.func,
onIdCodeSubmit: Types.func,
onAuthenticateWithIdCard: Types.func,
isAuthenticated: Types.bool,
phoneNumber: Types.string,
personalCode: Types.string,
controlCode: Types.string,
loadingAuthentication: Types.bool,
loadingUserConversion: Types.bool,
errorDescription: Types.string,
monthlyThirdPillarContribution: Types.number,
exchangeExistingThirdPillarUnits: Types.bool,
location: Types.shape({ state: { from: Types.string } }),
};
const mapStateToProps = (state) => ({
isAuthenticated: !!state.login.token,
phoneNumber: state.login.phoneNumber,
personalCode: state.login.personalCode,
controlCode: state.login.controlCode,
loadingAuthentication: state.login.loadingAuthentication,
loadingUserConversion: state.login.loadingUserConversion,
errorDescription: state.login.error || state.login.userConversionError,
monthlyThirdPillarContribution: state.thirdPillar.monthlyContribution,
exchangeExistingThirdPillarUnits: state.thirdPillar.exchangeExistingUnits,
});
const mapDispatchToProps = (dispatch) =>
bindActionCreators(
{
onPhoneNumberChange: changePhoneNumber,
onPersonalCodeChange: changePersonalCode,
onMobileIdSubmit: authenticateWithMobileId,
onCancelMobileAuthentication: cancelMobileAuthentication,
onIdCodeSubmit: authenticateWithIdCode,
onAuthenticateWithIdCard: authenticateWithIdCard,
},
dispatch,
);
const withRedux = connect(mapStateToProps, mapDispatchToProps);
export default withRouter(withRedux(LoginPage));
|
docs/src/app/components/pages/get-started/Installation.js | frnk94/material-ui | import React from 'react';
import Title from 'react-title-component';
import MarkdownElement from '../../MarkdownElement';
import installationText from './installation.md';
const Installation = () => (
<div>
<Title render={(previousTitle) => `Installation - ${previousTitle}`} />
<MarkdownElement text={installationText} />
</div>
);
export default Installation;
|
docs/pages/blog/2020-q1-update.js | lgollut/material-ui | import React from 'react';
import TopLayoutBlog from 'docs/src/modules/components/TopLayoutBlog';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'blog/2020-q1-update';
const requireRaw = require.context('!raw-loader!./', false, /2020-q1-update\.md$/);
export default function Page({ docs }) {
return <TopLayoutBlog docs={docs} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
app/components/ToggleOption/index.js | FlorianVoct/monPropreMix | /**
*
* ToggleOption
*
*/
import React from 'react';
import { injectIntl, intlShape } from 'react-intl';
const ToggleOption = ({ value, message, intl }) => (
<option value={value}>
{message ? intl.formatMessage(message) : value}
</option>
);
ToggleOption.propTypes = {
value: React.PropTypes.string.isRequired,
message: React.PropTypes.object,
intl: intlShape.isRequired,
};
export default injectIntl(ToggleOption);
|
packages/ringcentral-widgets-docs/src/app/pages/Components/CallingSettingsAlert/index.js | ringcentral/ringcentral-js-widget | import React from 'react';
import { parse } from 'react-docgen';
import CodeExample from '../../../components/CodeExample';
import ComponentHeader from '../../../components/ComponentHeader';
import PropTypeDescription from '../../../components/PropTypeDescription';
import Demo from './Demo';
// eslint-disable-next-line
import demoCode from '!raw-loader!./Demo';
// eslint-disable-next-line
import componentCode from '!raw-loader!ringcentral-widgets/components/AlertRenderer/CallingSettingsAlert';
const CallingSettingsAlertPage = () => {
const info = parse(componentCode);
return (
<div>
<ComponentHeader
name="CallingSettingsAlert"
description={info.description}
/>
<CodeExample code={demoCode} title="CallingSettingsAlert Example">
<Demo />
</CodeExample>
<PropTypeDescription componentInfo={info} />
</div>
);
};
export default CallingSettingsAlertPage;
|
index.js | cornedor/react-native-video-player | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Image, ImageBackground, Platform, StyleSheet, Text, TextInput, TouchableOpacity, View, ViewPropTypes } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Video from 'react-native-video'; // eslint-disable-line
const BackgroundImage = ImageBackground || Image; // fall back to Image if RN < 0.46
let ViewPropTypesVar;
if (ViewPropTypes) {
ViewPropTypesVar = ViewPropTypes;
} else {
ViewPropTypesVar = View.propTypes;
}
const getDurationTime = (duration) => {
const padTimeValueString = (value) => value.toString().padStart(2, '0');
if (!Number.isFinite(duration)) return '';
let seconds = Math.floor(duration % 60), minutes = Math.floor((duration / 60) % 60), hours = Math.floor((duration / (60 * 60)) % 24);
const isHrsZero = hours === 0;
hours = isHrsZero ? 0 : padTimeValueString(hours);
minutes = padTimeValueString(minutes);
seconds = padTimeValueString(seconds);
if (isHrsZero) {
return minutes + ':' + seconds;
}
return hours + ':' + minutes + ':' + seconds;
};
const styles = StyleSheet.create({
preloadingPlaceholder: {
backgroundColor: 'black',
justifyContent: 'center',
alignItems: 'center',
},
thumbnail: {
backgroundColor: 'black',
justifyContent: 'center',
alignItems: 'center',
},
playButton: {
backgroundColor: 'rgba(0, 0, 0, 0.6)',
width: 64,
height: 64,
borderRadius: 32,
justifyContent: 'center',
alignItems: 'center',
},
playArrow: {
color: 'white',
},
video: Platform.Version >= 24 ? {} : {
backgroundColor: 'black',
},
controls: {
backgroundColor: 'rgba(0, 0, 0, 0.6)',
height: 48,
marginTop: -48,
flexDirection: 'row',
alignItems: 'center',
},
playControl: {
color: 'white',
padding: 8,
},
extraControl: {
color: 'white',
padding: 8,
},
seekBar: {
alignItems: 'center',
height: 30,
flexGrow: 1,
flexDirection: 'row',
paddingHorizontal: 10,
marginLeft: -10,
marginRight: -5,
},
seekBarFullWidth: {
marginLeft: 0,
marginRight: 0,
paddingHorizontal: 0,
marginTop: -3,
height: 3,
},
seekBarProgress: {
height: 3,
backgroundColor: '#F00',
},
seekBarKnob: {
width: 20,
height: 20,
marginHorizontal: -8,
marginVertical: -10,
borderRadius: 10,
backgroundColor: '#F00',
transform: [{ scale: 0.8 }],
zIndex: 1,
},
seekBarBackground: {
backgroundColor: 'rgba(255, 255, 255, 0.5)',
height: 3,
},
overlayButton: {
flex: 1,
},
activeDurationText: {
paddingLeft: 8,
paddingRight:0,
paddingBottom: 0,
paddingTop: 0
},
durationText: {
color: 'white'
}
});
export default class VideoPlayer extends Component {
constructor(props) {
super(props);
this.state = {
isStarted: props.autoplay,
isPlaying: props.autoplay,
hasEnded: false,
width: 200,
progress: 0,
isMuted: props.defaultMuted,
isControlsVisible: !props.hideControlsOnStart,
duration: 0,
isSeeking: false,
};
this.seekBarWidth = 200;
this.wasPlayingBeforeSeek = props.autoplay;
this.seekTouchStart = 0;
this.seekProgressStart = 0;
this.onLayout = this.onLayout.bind(this);
this.onStartPress = this.onStartPress.bind(this);
this.onProgress = this.onProgress.bind(this);
this.onEnd = this.onEnd.bind(this);
this.onLoad = this.onLoad.bind(this);
this.onPlayPress = this.onPlayPress.bind(this);
this.onMutePress = this.onMutePress.bind(this);
this.showControls = this.showControls.bind(this);
this.onToggleFullScreen = this.onToggleFullScreen.bind(this);
this.onSeekBarLayout = this.onSeekBarLayout.bind(this);
this.onSeekGrant = this.onSeekGrant.bind(this);
this.onSeekRelease = this.onSeekRelease.bind(this);
this.onSeek = this.onSeek.bind(this);
this.onSeekEvent = this.onSeekEvent.bind(this);
}
componentDidMount() {
if (this.props.autoplay) {
this.hideControls();
}
}
componentWillUnmount() {
if (this.controlsTimeout) {
clearTimeout(this.controlsTimeout);
this.controlsTimeout = null;
}
}
onLayout(event) {
const { width } = event.nativeEvent.layout;
this.setState({
width,
});
}
onStartPress() {
if (this.props.onStart) {
this.props.onStart();
}
this.setState(state => ({
isPlaying: true,
isStarted: true,
hasEnded: false,
progress: state.progress === 1 ? 0 : state.progress,
}));
this.hideControls();
}
onProgress(event) {
if (this.state.isSeeking) {
return;
}
if (this.props.onProgress) {
this.props.onProgress(event);
}
this.setState({
progress: event.currentTime / (this.props.duration || this.state.duration),
});
this.currentTime?.setNativeProps({ text: getDurationTime(event.currentTime) })
}
onEnd(event) {
if (this.props.onEnd) {
this.props.onEnd(event);
}
if (this.props.endWithThumbnail || this.props.endThumbnail) {
this.setState({ isStarted: false, hasEnded: true });
this.player.dismissFullscreenPlayer();
}
this.setState({ progress: 1 });
if (!this.props.loop) {
this.setState(
{ isPlaying: false },
() => this.player && this.player.seek(0)
);
} else {
this.player.seek(0);
}
this.currentTime?.setNativeProps({ text: getDurationTime(this.state.duration) })
}
onLoad(event) {
if (this.props.onLoad) {
this.props.onLoad(event);
}
const { duration } = event;
this.setState({ duration });
}
onPlayPress() {
if (this.props.onPlayPress) {
this.props.onPlayPress();
}
this.setState({
isPlaying: !this.state.isPlaying,
});
this.showControls();
}
onMutePress() {
const isMuted = !this.state.isMuted;
if (this.props.onMutePress) {
this.props.onMutePress(isMuted);
}
this.setState({
isMuted,
});
this.showControls();
}
onToggleFullScreen() {
this.player.presentFullscreenPlayer();
}
onSeekBarLayout({ nativeEvent }) {
const customStyle = this.props.customStyles.seekBar;
let padding = 0;
if (customStyle && customStyle.paddingHorizontal) {
padding = customStyle.paddingHorizontal * 2;
} else if (customStyle) {
padding = customStyle.paddingLeft || 0;
padding += customStyle.paddingRight ? customStyle.paddingRight : 0;
} else {
padding = 20;
}
this.seekBarWidth = nativeEvent.layout.width - padding;
}
onSeekStartResponder() {
return true;
}
onSeekMoveResponder() {
return true;
}
onSeekGrant(e) {
this.seekTouchStart = e.nativeEvent.pageX;
this.seekProgressStart = this.state.progress;
this.wasPlayingBeforeSeek = this.state.isPlaying;
this.setState({
isSeeking: true,
isPlaying: false,
});
}
onSeekRelease() {
this.setState({
isSeeking: false,
isPlaying: this.wasPlayingBeforeSeek,
});
this.showControls();
}
onSeek(e) {
const diff = e.nativeEvent.pageX - this.seekTouchStart;
const ratio = 100 / this.seekBarWidth;
const progress = this.seekProgressStart + ((ratio * diff) / 100);
this.setState({
progress,
});
this.player.seek(progress * this.state.duration);
}
onSeekEvent(e) {
this.currentTime?.setNativeProps({ text: getDurationTime(e.currentTime) })
}
getSizeStyles() {
const { videoWidth, videoHeight } = this.props;
const { width } = this.state;
const ratio = videoHeight / videoWidth;
return {
height: width * ratio,
width,
};
}
hideControls() {
if (this.props.onHideControls) {
this.props.onHideControls();
}
if (this.props.disableControlsAutoHide) {
return;
}
if (this.controlsTimeout) {
clearTimeout(this.controlsTimeout);
this.controlsTimeout = null;
}
this.controlsTimeout = setTimeout(() => {
this.setState({ isControlsVisible: false });
}, this.props.controlsTimeout);
}
showControls() {
if (this.props.onShowControls) {
this.props.onShowControls();
}
this.setState({
isControlsVisible: true,
});
this.hideControls();
}
seek(t) {
this.player.seek(t);
}
stop() {
this.setState({
isPlaying: false,
progress: 0,
});
this.seek(0);
this.showControls();
}
pause() {
this.setState({
isPlaying: false,
});
this.showControls();
}
resume() {
this.setState({
isPlaying: true,
});
this.showControls();
}
renderStartButton() {
const { customStyles } = this.props;
return (
<TouchableOpacity
style={[styles.playButton, customStyles.playButton]}
onPress={this.onStartPress}
>
<Icon style={[styles.playArrow, customStyles.playArrow]} name="play-arrow" size={42} />
</TouchableOpacity>
);
}
renderThumbnail(thumbnail) {
const { style, customStyles, ...props } = this.props;
return (
<BackgroundImage
{...props}
style={[
styles.thumbnail,
this.getSizeStyles(),
style,
customStyles.thumbnail,
]}
source={thumbnail}
>
{this.renderStartButton()}
</BackgroundImage>
);
}
renderSeekBar(fullWidth) {
const { customStyles, disableSeek } = this.props;
return (
<View
style={[
styles.seekBar,
fullWidth ? styles.seekBarFullWidth : {},
customStyles.seekBar,
fullWidth ? customStyles.seekBarFullWidth : {},
]}
onLayout={this.onSeekBarLayout}
>
<View
style={[
{ flexGrow: this.state.progress },
styles.seekBarProgress,
customStyles.seekBarProgress,
]}
/>
{ !fullWidth && !disableSeek ? (
<View
style={[
styles.seekBarKnob,
customStyles.seekBarKnob,
this.state.isSeeking ? { transform: [{ scale: 1 }] } : {},
this.state.isSeeking ? customStyles.seekBarKnobSeeking : {},
]}
hitSlop={{ top: 20, bottom: 20, left: 10, right: 20 }}
onStartShouldSetResponder={this.onSeekStartResponder}
onMoveShouldSetPanResponder={this.onSeekMoveResponder}
onResponderGrant={this.onSeekGrant}
onResponderMove={this.onSeek}
onResponderRelease={this.onSeekRelease}
onResponderTerminate={this.onSeekRelease}
/>
) : null }
<View style={[
styles.seekBarBackground,
{ flexGrow: 1 - this.state.progress },
customStyles.seekBarBackground,
]} />
</View>
);
}
renderControls() {
const { customStyles, showDuration } = this.props;
return (
<View style={[styles.controls, customStyles.controls]}>
<TouchableOpacity
onPress={this.onPlayPress}
style={[customStyles.controlButton, customStyles.playControl]}
>
<Icon
style={[styles.playControl, customStyles.controlIcon, customStyles.playIcon]}
name={this.state.isPlaying ? 'pause' : 'play-arrow'}
size={32}
/>
</TouchableOpacity>
{this.renderSeekBar()}
{showDuration && (
<>
<TextInput style={[styles.durationText, styles.activeDurationText, customStyles.durationText]} editable={false} ref={e=> this.currentTime=e} value={getDurationTime(0)}/>
<Text style={[styles.durationText, customStyles.durationText]}>/</Text>
<Text style={[styles.durationText, customStyles.durationText]}>{getDurationTime(this.state.duration)}</Text>
</>
)}
{this.props.muted ? null : (
<TouchableOpacity onPress={this.onMutePress} style={customStyles.controlButton}>
<Icon
style={[styles.extraControl, customStyles.controlIcon]}
name={this.state.isMuted ? 'volume-off' : 'volume-up'}
size={24}
/>
</TouchableOpacity>
)}
{(Platform.OS === 'android' || this.props.disableFullscreen) ? null : (
<TouchableOpacity onPress={this.onToggleFullScreen} style={customStyles.controlButton}>
<Icon
style={[styles.extraControl, customStyles.controlIcon]}
name="fullscreen"
size={32}
/>
</TouchableOpacity>
)}
</View>
);
}
renderVideo() {
const {
video,
style,
resizeMode,
pauseOnPress,
fullScreenOnLongPress,
customStyles,
...props
} = this.props;
return (
<View style={customStyles.videoWrapper}>
<Video
{...props}
style={[
styles.video,
this.getSizeStyles(),
style,
customStyles.video,
]}
ref={p => { this.player = p; }}
muted={this.props.muted || this.state.isMuted}
paused={this.props.paused
? this.props.paused || !this.state.isPlaying
: !this.state.isPlaying}
onProgress={this.onProgress}
onEnd={this.onEnd}
onLoad={this.onLoad}
source={video}
resizeMode={resizeMode}
onSeek={this.onSeekEvent}
/>
<View
style={[
this.getSizeStyles(),
{ marginTop: -this.getSizeStyles().height },
]}
>
<TouchableOpacity
style={styles.overlayButton}
onPress={() => {
this.showControls();
if (pauseOnPress)
this.onPlayPress();
}}
onLongPress={() => {
if (fullScreenOnLongPress && Platform.OS !== 'android')
this.onToggleFullScreen();
}}
/>
</View>
{((!this.state.isPlaying) || this.state.isControlsVisible)
? this.renderControls() : this.renderSeekBar(true)}
</View>
);
}
renderContent() {
const { thumbnail, endThumbnail, style } = this.props;
const { isStarted, hasEnded } = this.state;
if (hasEnded && endThumbnail) {
return this.renderThumbnail(endThumbnail);
}
else if (!isStarted && thumbnail) {
return this.renderThumbnail(thumbnail);
} else if (!isStarted) {
return (
<View style={[styles.preloadingPlaceholder, this.getSizeStyles(), style]}>
{this.renderStartButton()}
</View>
);
}
return this.renderVideo();
}
render() {
return (
<View onLayout={this.onLayout} style={this.props.customStyles.wrapper}>
{this.renderContent()}
</View>
);
}
}
VideoPlayer.propTypes = {
video: Video.propTypes.source,
thumbnail: Image.propTypes.source,
endThumbnail: Image.propTypes.source,
videoWidth: PropTypes.number,
videoHeight: PropTypes.number,
duration: PropTypes.number,
autoplay: PropTypes.bool,
paused: PropTypes.bool,
defaultMuted: PropTypes.bool,
muted: PropTypes.bool,
style: ViewPropTypesVar.style,
controlsTimeout: PropTypes.number,
disableControlsAutoHide: PropTypes.bool,
disableFullscreen: PropTypes.bool,
loop: PropTypes.bool,
resizeMode: Video.propTypes.resizeMode,
hideControlsOnStart: PropTypes.bool,
endWithThumbnail: PropTypes.bool,
disableSeek: PropTypes.bool,
pauseOnPress: PropTypes.bool,
fullScreenOnLongPress: PropTypes.bool,
customStyles: PropTypes.shape({
wrapper: ViewPropTypesVar.style,
video: Video.propTypes.style,
videoWrapper: ViewPropTypesVar.style,
controls: ViewPropTypesVar.style,
playControl: ViewPropTypesVar.style,
controlButton: ViewPropTypesVar.style,
controlIcon: Icon.propTypes.style,
playIcon: Icon.propTypes.style,
seekBar: ViewPropTypesVar.style,
seekBarFullWidth: ViewPropTypesVar.style,
seekBarProgress: ViewPropTypesVar.style,
seekBarKnob: ViewPropTypesVar.style,
seekBarKnobSeeking: ViewPropTypesVar.style,
seekBarBackground: ViewPropTypesVar.style,
thumbnail: Image.propTypes.style,
playButton: ViewPropTypesVar.style,
playArrow: Icon.propTypes.style,
durationText: ViewPropTypesVar.style
}),
onEnd: PropTypes.func,
onProgress: PropTypes.func,
onLoad: PropTypes.func,
onStart: PropTypes.func,
onPlayPress: PropTypes.func,
onHideControls: PropTypes.func,
onShowControls: PropTypes.func,
onMutePress: PropTypes.func,
showDuration: PropTypes.bool
};
VideoPlayer.defaultProps = {
videoWidth: 1280,
videoHeight: 720,
autoplay: false,
controlsTimeout: 2000,
loop: false,
resizeMode: 'contain',
disableSeek: false,
pauseOnPress: false,
fullScreenOnLongPress: false,
customStyles: {},
showDuration: false
};
|
static/js/analytics.min.js | angelverde/web-admin-events | !function(){function require(path,parent,orig){var resolved=require.resolve(path);if(null==resolved){orig=orig||path;parent=parent||"root";var err=new Error('Failed to require "'+orig+'" from "'+parent+'"');err.path=orig;err.parent=parent;err.require=true;throw err}var module=require.modules[resolved];if(!module.exports){module.exports={};module.client=module.component=true;module.call(this,module.exports,require.relative(resolved),module)}return module.exports}require.modules={};require.aliases={};require.resolve=function(path){if(path.charAt(0)==="/")path=path.slice(1);var paths=[path,path+".js",path+".json",path+"/index.js",path+"/index.json"];for(var i=0;i<paths.length;i++){var path=paths[i];if(require.modules.hasOwnProperty(path))return path;if(require.aliases.hasOwnProperty(path))return require.aliases[path]}};require.normalize=function(curr,path){var segs=[];if("."!=path.charAt(0))return path;curr=curr.split("/");path=path.split("/");for(var i=0;i<path.length;++i){if(".."==path[i]){curr.pop()}else if("."!=path[i]&&""!=path[i]){segs.push(path[i])}}return curr.concat(segs).join("/")};require.register=function(path,definition){require.modules[path]=definition};require.alias=function(from,to){if(!require.modules.hasOwnProperty(from)){throw new Error('Failed to alias "'+from+'", it does not exist')}require.aliases[to]=from};require.relative=function(parent){var p=require.normalize(parent,"..");function lastIndexOf(arr,obj){var i=arr.length;while(i--){if(arr[i]===obj)return i}return-1}function localRequire(path){var resolved=localRequire.resolve(path);return require(resolved,parent,path)}localRequire.resolve=function(path){var c=path.charAt(0);if("/"==c)return path.slice(1);if("."==c)return require.normalize(p,path);var segs=parent.split("/");var i=lastIndexOf(segs,"deps")+1;if(!i)i=0;path=segs.slice(0,i+1).join("/")+"/deps/"+path;return path};localRequire.exists=function(path){return require.modules.hasOwnProperty(localRequire.resolve(path))};return localRequire};require.register("avetisk-defaults/index.js",function(exports,require,module){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults});require.register("component-clone/index.js",function(exports,require,module){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}});require.register("component-cookie/index.js",function(exports,require,module){var encode=encodeURIComponent;var decode=decodeURIComponent;module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toUTCString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}});require.register("component-each/index.js",function(exports,require,module){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}});require.register("component-event/index.js",function(exports,require,module){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}});require.register("component-inherit/index.js",function(exports,require,module){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}});require.register("component-object/index.js",function(exports,require,module){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}});require.register("component-trim/index.js",function(exports,require,module){exports=module.exports=trim;function trim(str){return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){return str.replace(/^\s*/,"")};exports.right=function(str){return str.replace(/\s*$/,"")}});require.register("component-querystring/index.js",function(exports,require,module){var trim=require("trim");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");obj[parts[0]]=null==parts[1]?"":decodeURIComponent(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){pairs.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key]))}return pairs.join("&")}});require.register("component-type/index.js",function(exports,require,module){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}});require.register("component-url/index.js",function(exports,require,module){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host||location.host,port:"0"===a.port||""===a.port?location.port:a.port,hash:a.hash,hostname:a.hostname||location.hostname,pathname:a.pathname.charAt(0)!="/"?"/"+a.pathname:a.pathname,protocol:!a.protocol||":"==a.protocol?location.protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){return 0==url.indexOf("//")||!!~url.indexOf("://")};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!==location.hostname||url.port!==location.port||url.protocol!==location.protocol}});require.register("segmentio-after/index.js",function(exports,require,module){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}});require.register("segmentio-alias/index.js",function(exports,require,module){module.exports=function alias(object,aliases){for(var oldKey in aliases){var newKey=aliases[oldKey];if(object[oldKey]!==undefined){object[newKey]=object[oldKey];delete object[oldKey]}}}});require.register("component-bind/index.js",function(exports,require,module){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=[].slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}});require.register("segmentio-bind-all/index.js",function(exports,require,module){var bind=require("bind"),type=require("type");module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}});require.register("segmentio-canonical/index.js",function(exports,require,module){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}});require.register("segmentio-extend/index.js",function(exports,require,module){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}});require.register("segmentio-is-email/index.js",function(exports,require,module){module.exports=function isEmail(string){return/.+\@.+\..+/.test(string)}});require.register("segmentio-is-meta/index.js",function(exports,require,module){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}});require.register("component-json-fallback/index.js",function(exports,require,module){var JSON={};!function(){"use strict";function f(n){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={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}}();module.exports=JSON});require.register("segmentio-json/index.js",function(exports,require,module){module.exports="undefined"==typeof JSON?require("json-fallback"):JSON});require.register("segmentio-load-date/index.js",function(exports,require,module){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time});require.register("segmentio-load-script/index.js",function(exports,require,module){var type=require("type");module.exports=function loadScript(options,callback){if(!options)throw new Error("Cant load nothing...");if(type(options)==="string")options={src:options};var https=document.location.protocol==="https:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript);if(callback&&type(callback)==="function"){if(script.addEventListener){script.addEventListener("load",callback,false)}else if(script.attachEvent){script.attachEvent("onreadystatechange",function(){if(/complete|loaded/.test(script.readyState))callback()})}}return script}});require.register("segmentio-type/index.js",function(exports,require,module){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}});require.register("segmentio-new-date/index.js",function(exports,require,module){var type=require("type");module.exports=function newDate(input){input=toMilliseconds(input);var date=new Date(input);if(isNaN(date.getTime())&&"string"===type(input)){var milliseconds=toMilliseconds(parseInt(input,10));date=new Date(milliseconds)}return date};function toMilliseconds(seconds){if("number"===type(seconds)&&seconds<315576e5)return seconds*1e3;return seconds}});require.register("segmentio-on-body/index.js",function(exports,require,module){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}});require.register("segmentio-store.js/store.js",function(exports,require,module){var json=require("json"),store={},win=window,doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return json.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return json.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;module.exports=store});require.register("segmentio-top-domain/index.js",function(exports,require,module){var url=require("url");module.exports=function(urlStr){var host=url.parse(urlStr).hostname,topLevel=host.match(/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i);return topLevel?topLevel[0]:host}});require.register("timoxley-next-tick/index.js",function(exports,require,module){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}});require.register("yields-prevent/index.js",function(exports,require,module){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}});require.register("analytics/src/index.js",function(exports,require,module){var Analytics=require("./analytics"),providers=require("./providers");module.exports=new Analytics(providers)});require.register("analytics/src/analytics.js",function(exports,require,module){var after=require("after"),bind=require("event").bind,clone=require("clone"),cookie=require("./cookie"),each=require("each"),extend=require("extend"),isEmail=require("is-email"),isMeta=require("is-meta"),localStore=require("./localStore"),newDate=require("new-date"),size=require("object").length,preventDefault=require("prevent"),Provider=require("./provider"),providers=require("./providers"),querystring=require("querystring"),type=require("type"),url=require("url"),user=require("./user"),utils=require("./utils");module.exports=Analytics;function Analytics(Providers){var self=this;this.VERSION="0.11.10";each(Providers,function(Provider){self.addProvider(Provider)});var oldonload=window.onload;window.onload=function(){self.loaded=true;if("function"===type(oldonload))oldonload()}}extend(Analytics.prototype,{loaded:false,initialized:false,readied:false,callbacks:[],timeout:300,user:user,Provider:Provider,_providers:{},providers:[],addProvider:function(Provider){this._providers[Provider.prototype.name]=Provider},initialize:function(providers,options){options||(options={});var self=this;this.providers=[];this.initialized=false;this.readied=false;cookie.options(options.cookie);localStore.options(options.localStorage);user.options(options.user);user.load();var ready=after(size(providers),function(){self.readied=true;var callback;while(callback=self.callbacks.shift()){callback()}});each(providers,function(key,options){var Provider=self._providers[key];if(!Provider)return;self.providers.push(new Provider(options,ready,self))});var query=url.parse(window.location.href).query;var queries=querystring.parse(query);if(queries.ajs_uid)this.identify(queries.ajs_uid);if(queries.ajs_event)this.track(queries.ajs_event);this.initialized=true},ready:function(callback){if(type(callback)!=="function")return;if(this.readied)return callback();this.callbacks.push(callback)},identify:function(userId,traits,options,callback){if(!this.initialized)return;if(type(options)==="function"){callback=options;options=undefined}if(type(traits)==="function"){callback=traits;traits=undefined}if(type(userId)==="object"){if(traits&&type(traits)==="function")callback=traits;traits=userId;userId=undefined}if(userId===undefined||user===null)userId=user.id();var alias=user.update(userId,traits);traits=cleanTraits(userId,clone(user.traits()));each(this.providers,function(provider){if(provider.identify&&isEnabled(provider,options)){var args=[userId,clone(traits),clone(options)];if(provider.ready){provider.identify.apply(provider,args)}else{provider.enqueue("identify",args)}}});if(callback&&type(callback)==="function"){setTimeout(callback,this.timeout)}},group:function(groupId,properties,options,callback){if(!this.initialized)return;if(type(options)==="function"){callback=options;options=undefined}if(type(properties)==="function"){callback=properties;properties=undefined}properties=clone(properties)||{};if(properties.created)properties.created=newDate(properties.created);each(this.providers,function(provider){if(provider.group&&isEnabled(provider,options)){var args=[groupId,clone(properties),clone(options)];if(provider.ready){provider.group.apply(provider,args)}else{provider.enqueue("group",args)}}});if(callback&&type(callback)==="function"){setTimeout(callback,this.timeout)}},track:function(event,properties,options,callback){if(!this.initialized)return;if(type(options)==="function"){callback=options;options=undefined}if(type(properties)==="function"){callback=properties;properties=undefined}each(this.providers,function(provider){if(provider.track&&isEnabled(provider,options)){var args=[event,clone(properties),clone(options)];if(provider.ready){provider.track.apply(provider,args)}else{provider.enqueue("track",args)}}});if(callback&&type(callback)==="function"){setTimeout(callback,this.timeout)}},trackLink:function(links,event,properties){if(!links)return;if("element"===type(links))links=[links];var self=this,eventFunction="function"===type(event),propertiesFunction="function"===type(properties);each(links,function(el){bind(el,"click",function(e){var newEvent=eventFunction?event(el):event;var newProperties=propertiesFunction?properties(el):properties;self.track(newEvent,newProperties);if(el.href&&el.target!=="_blank"&&!isMeta(e)){preventDefault(e);setTimeout(function(){window.location.href=el.href},self.timeout)}})})},trackForm:function(form,event,properties){if(!form)return;if("element"===type(form))form=[form];var self=this,eventFunction="function"===type(event),propertiesFunction="function"===type(properties);each(form,function(el){var handler=function(e){var newEvent=eventFunction?event(el):event;var newProperties=propertiesFunction?properties(el):properties;self.track(newEvent,newProperties);preventDefault(e);setTimeout(function(){el.submit()},self.timeout)};var dom=window.jQuery||window.Zepto;if(dom){dom(el).submit(handler)}else{bind(el,"submit",handler)}})},pageview:function(url,options){if(!this.initialized)return;each(this.providers,function(provider){if(provider.pageview&&isEnabled(provider,options)){var args=[url];if(provider.ready){provider.pageview.apply(provider,args)}else{provider.enqueue("pageview",args)}}})},alias:function(newId,originalId,options){if(!this.initialized)return;if(type(originalId)==="object"){options=originalId;originalId=undefined}each(this.providers,function(provider){if(provider.alias&&isEnabled(provider,options)){var args=[newId,originalId];if(provider.ready){provider.alias.apply(provider,args)}else{provider.enqueue("alias",args)}}})},log:function(error,properties,options){if(!this.initialized)return;each(this.providers,function(provider){if(provider.log&&isEnabled(provider,options)){var args=[error,properties,options];if(provider.ready){provider.log.apply(provider,args)}else{provider.enqueue("log",args)}}})}});Analytics.prototype.trackClick=Analytics.prototype.trackLink;Analytics.prototype.trackSubmit=Analytics.prototype.trackForm;var isEnabled=function(provider,options){var enabled=true;if(!options||!options.providers)return enabled;var map=options.providers;if(map.all!==undefined)enabled=map.all;if(map.All!==undefined)enabled=map.All;var name=provider.name;if(map[name]!==undefined)enabled=map[name];return enabled};var cleanTraits=function(userId,traits){if(!traits.email&&isEmail(userId))traits.email=userId;if(!traits.name&&traits.firstName&&traits.lastName){traits.name=traits.firstName+" "+traits.lastName}if(traits.created)traits.created=newDate(traits.created);if(traits.company&&traits.company.created){traits.company.created=newDate(traits.company.created)}return traits}});require.register("analytics/src/cookie.js",function(exports,require,module){var bindAll=require("bind-all"),cookie=require("cookie"),clone=require("clone"),defaults=require("defaults"),json=require("json"),topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});var domain="."+topDomain(window.location.href);if(domain===".localhost")domain="";defaults(options,{maxage:31536e6,path:"/",domain:domain});this._options=options};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bindAll(new Cookie);module.exports.Cookie=Cookie});require.register("analytics/src/localStore.js",function(exports,require,module){var bindAll=require("bind-all"),defaults=require("defaults"),store=require("store");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bindAll(new Store)});require.register("analytics/src/provider.js",function(exports,require,module){var each=require("each"),extend=require("extend"),type=require("type");module.exports=Provider;function Provider(options,ready,analytics){var self=this;this.analytics=analytics;this.queue=[];this.ready=false;if(type(options)!=="object"){if(options===true){options={}}else if(this.key){var key=options;options={};options[this.key]=key}else{throw new Error("Couldnt resolve options.")}}this.options=extend({},this.defaults,options);var dequeue=function(){each(self.queue,function(call){var method=call.method,args=call.args;self[method].apply(self,args)});self.ready=true;self.queue=[];ready()};this.initialize.call(this,this.options,dequeue)}Provider.extend=function(properties){var parent=this;var child=function(){return parent.apply(this,arguments)};var Surrogate=function(){this.constructor=child};Surrogate.prototype=parent.prototype;child.prototype=new Surrogate;extend(child.prototype,properties);return child};extend(Provider.prototype,{options:{},key:undefined,initialize:function(options,ready){ready()},enqueue:function(method,args){this.queue.push({method:method,args:args})}})});require.register("analytics/src/user.js",function(exports,require,module){var bindAll=require("bind-all"),clone=require("clone"),cookie=require("./cookie"),defaults=require("defaults"),extend=require("extend"),localStore=require("./localStore");function User(options){this._id=null;this._traits={};this.options(options)}User.prototype.options=function(options){options||(options={});defaults(options,{persist:true});this.cookie(options.cookie);this.localStorage(options.localStorage);this.persist=options.persist};User.prototype.cookie=function(options){if(arguments.length===0)return this.cookieOptions;options||(options={});defaults(options,{key:"ajs_user_id",oldKey:"ajs_user"});this.cookieOptions=options};User.prototype.localStorage=function(options){if(arguments.length===0)return this.localStorageOptions;options||(options={});defaults(options,{key:"ajs_user_traits"});this.localStorageOptions=options};User.prototype.id=function(id){if(arguments.length===0)return this._id;this._id=id};User.prototype.traits=function(traits){if(arguments.length===0)return clone(this._traits);traits||(traits={});this._traits=traits};User.prototype.update=function(userId,traits){var alias=!this.id()&&userId&&this.persist;traits||(traits={});if(this.id()&&userId&&this.id()!==userId)this.traits(traits);
else this.traits(extend(this.traits(),traits));if(userId)this.id(userId);this.save();return alias};User.prototype.save=function(){if(!this.persist)return false;cookie.set(this.cookie().key,this.id());localStore.set(this.localStorage().key,this.traits());return true};User.prototype.load=function(){if(this.loadOldCookie())return this.toJSON();var id=cookie.get(this.cookie().key),traits=localStore.get(this.localStorage().key);this.id(id);this.traits(traits);return this.toJSON()};User.prototype.clear=function(){cookie.remove(this.cookie().key);localStore.remove(this.localStorage().key);this.id(null);this.traits({})};User.prototype.loadOldCookie=function(){var user=cookie.get(this.cookie().oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this.cookie().oldKey);return true};User.prototype.toJSON=function(){return{id:this.id(),traits:this.traits()}};module.exports=bindAll(new User)});require.register("analytics/src/utils.js",function(exports,require,module){exports.getUrlParameter=function(urlSearchParameter,paramKey){var params=urlSearchParameter.replace("?","").split("&");for(var i=0;i<params.length;i+=1){var param=params[i].split("=");if(param.length===2&¶m[0]===paramKey){return decodeURIComponent(param[1])}}}});require.register("analytics/src/providers/adroll.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"AdRoll",defaults:{advId:null,pixId:null},initialize:function(options,ready){window.adroll_adv_id=options.advId;window.adroll_pix_id=options.pixId;window.__adroll_loaded=true;load({http:"http://a.adroll.com/j/roundtrip.js",https:"https://s.adroll.com/j/roundtrip.js"},ready)}})});require.register("analytics/src/providers/amplitude.js",function(exports,require,module){var Provider=require("../provider"),alias=require("alias"),load=require("load-script");module.exports=Provider.extend({name:"Amplitude",key:"apiKey",defaults:{apiKey:null,pageview:false},initialize:function(options,ready){!function(e,t){var r=e.amplitude||{};r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName"];for(var c=0;c<s.length;c++){i(s[c])}e.amplitude=r}(window,document);load("https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.0-min.js");window.amplitude.init(options.apiKey);ready()},identify:function(userId,traits){if(userId)window.amplitude.setUserId(userId);if(traits)window.amplitude.setGlobalUserProperties(traits)},track:function(event,properties){window.amplitude.logEvent(event,properties)},pageview:function(url){if(!this.options.pageview)return;var properties={url:url||document.location.href,name:document.title};this.track("Loaded a Page",properties)}})});require.register("analytics/src/providers/bitdeli.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Bitdeli",defaults:{inputId:null,authToken:null,initialPageview:true},initialize:function(options,ready){window._bdq=window._bdq||[];window._bdq.push(["setAccount",options.inputId,options.authToken]);if(options.initialPageview)this.pageview();load("//d2flrkr957qc5j.cloudfront.net/bitdeli.min.js");ready()},identify:function(userId,traits){if(userId)window._bdq.push(["identify",userId]);if(traits)window._bdq.push(["set",traits])},track:function(event,properties){window._bdq.push(["track",event,properties])},pageview:function(url){window._bdq.push(["trackPageview",url])}})});require.register("analytics/src/providers/bugherd.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"BugHerd",key:"apiKey",defaults:{apiKey:null,showFeedbackTab:true},initialize:function(options,ready){if(!options.showFeedbackTab){window.BugHerdConfig={feedback:{hide:true}}}load("//www.bugherd.com/sidebarv2.js?apikey="+options.apiKey,ready)}})});require.register("analytics/src/providers/chartbeat.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Chartbeat",defaults:{domain:null,uid:null},initialize:function(options,ready){window._sf_async_config=options;var loadChartbeat=function(){if(!document.body)return setTimeout(loadChartbeat,5);window._sf_endpt=(new Date).getTime();load({https:"https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/js/chartbeat.js",http:"http://static.chartbeat.com/js/chartbeat.js"},ready)};loadChartbeat()},pageview:function(url){if(!window.pSUPERFLY)return;window.pSUPERFLY.virtualPage(url||window.location.pathname)}})});require.register("analytics/src/providers/clicktale.js",function(exports,require,module){var date=require("load-date"),Provider=require("../provider"),load=require("load-script"),onBody=require("on-body");module.exports=Provider.extend({name:"ClickTale",key:"projectId",defaults:{httpCdnUrl:"http://s.clicktale.net/WRe0.js",httpsCdnUrl:null,projectId:null,recordingRatio:.01,partitionId:null},initialize:function(options,ready){if(document.location.protocol==="https:"&&!options.httpsCdnUrl)return;window.WRInitTime=date.getTime();onBody(function(body){var div=document.createElement("div");div.setAttribute("id","ClickTaleDiv");div.setAttribute("style","display: none;");body.appendChild(div)});var onloaded=function(){window.ClickTale(options.projectId,options.recordingRatio,options.partitionId);ready()};load({http:options.httpCdnUrl,https:options.httpsCdnUrl},onloaded)},identify:function(userId,traits){if(window.ClickTaleSetUID)window.ClickTaleSetUID(userId);if(window.ClickTaleField){for(var traitKey in traits){window.ClickTaleField(traitKey,traits[traitKey])}}},track:function(event,properties){if(window.ClickTaleEvent)window.ClickTaleEvent(event)}})});require.register("analytics/src/providers/clicky.js",function(exports,require,module){var Provider=require("../provider"),user=require("../user"),extend=require("extend"),load=require("load-script");module.exports=Provider.extend({name:"Clicky",key:"siteId",defaults:{siteId:null},initialize:function(options,ready){window.clicky_site_ids=window.clicky_site_ids||[];window.clicky_site_ids.push(options.siteId);var userId=user.id(),traits=user.traits(),session={};if(userId)session.id=userId;extend(session,traits);window.clicky_custom={session:session};load("//static.getclicky.com/js",ready)},track:function(event,properties){window.clicky.log(window.location.href,event)}})});require.register("analytics/src/providers/comscore.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"comScore",key:"c2",defaults:{c1:"2",c2:null},initialize:function(options,ready){window._comscore=window._comscore||[];window._comscore.push(options);load({http:"http://b.scorecardresearch.com/beacon.js",https:"https://sb.scorecardresearch.com/beacon.js"},ready)}})});require.register("analytics/src/providers/crazyegg.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"CrazyEgg",key:"accountNumber",defaults:{accountNumber:null},initialize:function(options,ready){var accountPath=options.accountNumber.slice(0,4)+"/"+options.accountNumber.slice(4);load("//dnn506yrbagrg.cloudfront.net/pages/scripts/"+accountPath+".js?"+Math.floor((new Date).getTime()/36e5),ready)}})});require.register("analytics/src/providers/customerio.js",function(exports,require,module){var Provider=require("../provider"),isEmail=require("is-email"),load=require("load-script");module.exports=Provider.extend({name:"Customer.io",key:"siteId",defaults:{siteId:null},initialize:function(options,ready){var _cio=window._cio=window._cio||[];!function(){var a,b,c;a=function(f){return function(){_cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){_cio[b[c]]=a(b[c])}}();var script=load("https://assets.customer.io/assets/track.js");script.id="cio-tracker";script.setAttribute("data-site-id",options.siteId);ready()},identify:function(userId,traits){if(!userId)return;traits.id=userId;if(traits.created){traits.created_at=Math.floor(traits.created/1e3);delete traits.created}window._cio.identify(traits)},track:function(event,properties){window._cio.track(event,properties)}})});require.register("analytics/src/providers/errorception.js",function(exports,require,module){var Provider=require("../provider"),extend=require("extend"),load=require("load-script"),type=require("type");module.exports=Provider.extend({name:"Errorception",key:"projectId",defaults:{projectId:null,meta:true},initialize:function(options,ready){window._errs=window._errs||[options.projectId];load("//d15qhc0lu1ghnk.cloudfront.net/beacon.js");var oldOnError=window.onerror;window.onerror=function(){window._errs.push(arguments);if("function"===type(oldOnError)){oldOnError.apply(this,arguments)}};ready()},identify:function(userId,traits){if(!this.options.meta)return;window._errs.meta||(window._errs.meta={});traits.id=userId;extend(window._errs.meta,traits)}})});require.register("analytics/src/providers/foxmetrics.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"FoxMetrics",key:"appId",defaults:{appId:null},initialize:function(options,ready){var _fxm=window._fxm||{};window._fxm=_fxm.events||[];load("//d35tca7vmefkrc.cloudfront.net/scripts/"+options.appId+".js");ready()},identify:function(userId,traits){if(!userId)return;var firstName=traits.firstName,lastName=traits.lastName;if(!firstName&&traits.name)firstName=traits.name.split(" ")[0];if(!lastName&&traits.name)lastName=traits.name.split(" ")[1];window._fxm.push(["_fxm.visitor.profile",userId,firstName,lastName,traits.email,traits.address,undefined,undefined,traits])},track:function(event,properties){window._fxm.push([event,properties.category,properties])},pageview:function(url){window._fxm.push(["_fxm.pages.view",undefined,undefined,undefined,url,undefined])}})});require.register("analytics/src/providers/gauges.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Gauges",key:"siteId",defaults:{siteId:null},initialize:function(options,ready){window._gauges=window._gauges||[];var script=load("//secure.gaug.es/track.js");script.id="gauges-tracker";script.setAttribute("data-site-id",options.siteId);ready()},pageview:function(url){window._gauges.push(["track"])}})});require.register("analytics/src/providers/get-satisfaction.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script"),onBody=require("on-body");module.exports=Provider.extend({name:"Get Satisfaction",key:"widgetId",defaults:{widgetId:null},initialize:function(options,ready){var div=document.createElement("div");var id=div.id="getsat-widget-"+options.widgetId;onBody(function(body){body.appendChild(div)});load("https://loader.engage.gsfn.us/loader.js",function(){if(window.GSFN!==undefined){window.GSFN.loadWidget(options.widgetId,{containerId:id})}ready()})}})});require.register("analytics/src/providers/google-analytics.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script"),type=require("type"),url=require("url"),canonical=require("canonical");module.exports=Provider.extend({name:"Google Analytics",key:"trackingId",defaults:{anonymizeIp:false,domain:null,doubleClick:false,enhancedLinkAttribution:false,ignoreReferrer:null,initialPageview:true,siteSpeedSampleRate:null,trackingId:null,universalClient:false},initialize:function(options,ready){if(options.universalClient)this.initializeUniversal(options,ready);else this.initializeClassic(options,ready)},initializeClassic:function(options,ready){window._gaq=window._gaq||[];window._gaq.push(["_setAccount",options.trackingId]);if(options.domain){window._gaq.push(["_setDomainName",options.domain])}if(options.enhancedLinkAttribution){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";window._gaq.push(["_require","inpage_linkid",pluginUrl])}if(type(options.siteSpeedSampleRate)==="number"){window._gaq.push(["_setSiteSpeedSampleRate",options.siteSpeedSampleRate])}if(options.anonymizeIp){window._gaq.push(["_gat._anonymizeIp"])}if(options.ignoreReferrer){window._gaq.push(["_addIgnoredRef",options.ignoreReferrer])}if(options.initialPageview){var path,canon=canonical();if(canon)path=url.parse(canon).pathname;this.pageview(path)}if(options.doubleClick){load("//stats.g.doubleclick.net/dc.js",ready)}else{load({http:"http://www.google-analytics.com/ga.js",https:"https://ssl.google-analytics.com/ga.js"},ready)}},initializeUniversal:function(options,ready){var global=this.global="ga";window["GoogleAnalyticsObject"]=global;window[global]=window[global]||function(){(window[global].q=window[global].q||[]).push(arguments)};window[global].l=1*new Date;var createOpts={};if(options.domain)createOpts.cookieDomain=options.domain||"none";if(type(options.siteSpeedSampleRate)==="number")createOpts.siteSpeedSampleRate=options.siteSpeedSampleRate;if(options.anonymizeIp)ga("set","anonymizeIp",true);ga("create",options.trackingId,createOpts);if(options.initialPageview){var path,canon=canonical();if(canon)path=url.parse(canon).pathname;this.pageview(path)}load("//www.google-analytics.com/analytics.js");ready()},track:function(event,properties){properties||(properties={});var value;if(type(properties.value)==="number")value=Math.round(properties.value);if(this.options.universalClient){var opts={};if(properties.noninteraction)opts.nonInteraction=properties.noninteraction;window[this.global]("send","event",properties.category||"All",event,properties.label,Math.round(properties.revenue)||value,opts)}else{window._gaq.push(["_trackEvent",properties.category||"All",event,properties.label,Math.round(properties.revenue)||value,properties.noninteraction])}},pageview:function(url){if(this.options.universalClient){window[this.global]("send","pageview",url)}else{window._gaq.push(["_trackPageview",url])}}})});require.register("analytics/src/providers/gosquared.js",function(exports,require,module){var Provider=require("../provider"),user=require("../user"),load=require("load-script"),onBody=require("on-body");module.exports=Provider.extend({name:"GoSquared",key:"siteToken",defaults:{siteToken:null},initialize:function(options,ready){onBody(function(){var GoSquared=window.GoSquared={};GoSquared.acct=options.siteToken;GoSquared.q=[];window._gstc_lt=+new Date;GoSquared.VisitorName=user.id();GoSquared.Visitor=user.traits();load("//d1l6p2sc9645hc.cloudfront.net/tracker.js");ready()})},identify:function(userId,traits){if(userId)window.GoSquared.UserName=userId;if(traits)window.GoSquared.Visitor=traits},track:function(event,properties){window.GoSquared.q.push(["TrackEvent",event,properties||{}])},pageview:function(url){window.GoSquared.q.push(["TrackView",url])}})});require.register("analytics/src/providers/heap.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Heap",key:"apiKey",defaults:{apiKey:null},initialize:function(options,ready){window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var b=document.createElement("script");b.type="text/javascript",b.async=!0,b.src=("https:"===document.location.protocol?"https:":"http:")+"//d36lvucg9kzous.cloudfront.net";var c=document.getElementsByTagName("script")[0];c.parentNode.insertBefore(b,c);var d=function(a){return function(){heap.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track"];for(var f=0;f<e.length;f++)heap[e[f]]=d(e[f])};window.heap.load(options.apiKey);ready()},identify:function(userId,traits){window.heap.identify(traits)},track:function(event,properties){window.heap.track(event,properties)}})});require.register("analytics/src/providers/hittail.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"HitTail",key:"siteId",defaults:{siteId:null},initialize:function(options,ready){load("//"+options.siteId+".hittail.com/mlt.js",ready)}})});require.register("analytics/src/providers/hubspot.js",function(exports,require,module){var Provider=require("../provider"),isEmail=require("is-email"),load=require("load-script");module.exports=Provider.extend({name:"HubSpot",key:"portalId",defaults:{portalId:null},initialize:function(options,ready){if(!document.getElementById("hs-analytics")){window._hsq=window._hsq||[];var script=load("https://js.hubspot.com/analytics/"+Math.ceil(new Date/3e5)*3e5+"/"+options.portalId+".js");script.id="hs-analytics"}ready()},identify:function(userId,traits){window._hsq.push(["identify",traits])},track:function(event,properties){window._hsq.push(["trackEvent",event,properties])},pageview:function(url){window._hsq.push(["_trackPageview"])}})});require.register("analytics/src/providers/index.js",function(exports,require,module){module.exports=[require("./adroll"),require("./amplitude"),require("./bitdeli"),require("./bugherd"),require("./chartbeat"),require("./clicktale"),require("./clicky"),require("./comscore"),require("./crazyegg"),require("./customerio"),require("./errorception"),require("./foxmetrics"),require("./gauges"),require("./get-satisfaction"),require("./google-analytics"),require("./gosquared"),require("./heap"),require("./hittail"),require("./hubspot"),require("./improvely"),require("./intercom"),require("./keen-io"),require("./kissmetrics"),require("./klaviyo"),require("./livechat"),require("./lytics"),require("./mixpanel"),require("./olark"),require("./optimizely"),require("./perfect-audience"),require("./pingdom"),require("./preact"),require("./qualaroo"),require("./quantcast"),require("./sentry"),require("./snapengage"),require("./usercycle"),require("./userfox"),require("./uservoice"),require("./vero"),require("./visual-website-optimizer"),require("./woopra")]});require.register("analytics/src/providers/improvely.js",function(exports,require,module){var Provider=require("../provider"),alias=require("alias"),load=require("load-script");module.exports=Provider.extend({name:"Improvely",defaults:{domain:null,projectId:null},initialize:function(options,ready){window._improvely=window._improvely||[];window.improvely=window.improvely||{init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};load("//"+options.domain+".iljmp.com/improvely.js");window.improvely.init(options.domain,options.projectId);ready()},identify:function(userId,traits){if(userId)window.improvely.label(userId)},track:function(event,properties){properties||(properties={});properties.type=event;alias(properties,{revenue:"amount"});window.improvely.goal(properties)}})});require.register("analytics/src/providers/intercom.js",function(exports,require,module){var Provider=require("../provider"),extend=require("extend"),load=require("load-script"),isEmail=require("is-email");module.exports=Provider.extend({name:"Intercom",booted:false,key:"appId",defaults:{appId:null,activator:null,counter:true},initialize:function(options,ready){load("https://static.intercomcdn.com/intercom.v1.js",ready)},identify:function(userId,traits,options){if(!this.booted&&!userId)return;options||(options={});var Intercom=options.Intercom||options.intercom||{};traits.increments=Intercom.increments;traits.user_hash=Intercom.userHash||Intercom.user_hash;if(traits.created){traits.created_at=Math.floor(traits.created/1e3);delete traits.created}if(traits.company&&traits.company.created){traits.company.created_at=Math.floor(traits.company.created/1e3);delete traits.company.created}if(this.options.activator){traits.widget={activator:this.options.activator,use_counter:this.options.counter}}if(this.booted){window.Intercom("update",traits)}else{extend(traits,{app_id:this.options.appId,user_id:userId});window.Intercom("boot",traits)}this.booted=true},group:function(groupId,properties,options){properties.id=groupId;window.Intercom("update",{company:properties})}})});require.register("analytics/src/providers/keen-io.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Keen IO",defaults:{projectId:null,writeKey:null,readKey:null,pageview:true,initialPageview:true},initialize:function(options,ready){window.Keen=window.Keen||{configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e)}};window.Keen.configure({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});load("//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js");if(options.initialPageview)this.pageview();ready()},identify:function(userId,traits){var globalUserProps={};if(userId)globalUserProps.userId=userId;if(traits)globalUserProps.traits=traits;if(userId||traits){window.Keen.setGlobalProperties(function(eventCollection){return{user:globalUserProps}})}},track:function(event,properties){window.Keen.addEvent(event,properties)},pageview:function(url){if(!this.options.pageview)return;var properties={url:url||document.location.href,name:document.title};this.track("Loaded a Page",properties)}})});require.register("analytics/src/providers/kissmetrics.js",function(exports,require,module){var Provider=require("../provider"),alias=require("alias"),load=require("load-script");module.exports=Provider.extend({name:"KISSmetrics",key:"apiKey",defaults:{apiKey:null},initialize:function(options,ready){window._kmq=window._kmq||[];load("//i.kissmetrics.com/i.js");load("//doug1izaerwt3.cloudfront.net/"+options.apiKey+".1.js");ready()},identify:function(userId,traits){if(userId)window._kmq.push(["identify",userId]);if(traits)window._kmq.push(["set",traits])},track:function(event,properties){if(properties){alias(properties,{revenue:"Billing Amount"})}window._kmq.push(["record",event,properties])},alias:function(newId,originalId){window._kmq.push(["alias",newId,originalId])}})});require.register("analytics/src/providers/klaviyo.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Klaviyo",key:"apiKey",defaults:{apiKey:null},initialize:function(options,ready){window._learnq=window._learnq||[];window._learnq.push(["account",options.apiKey]);load("//a.klaviyo.com/media/js/learnmarklet.js");ready()},identify:function(userId,traits){if(!userId)return;traits.$id=userId;window._learnq.push(["identify",traits])},track:function(event,properties){window._learnq.push(["track",event,properties])}})});require.register("analytics/src/providers/livechat.js",function(exports,require,module){var Provider=require("../provider"),each=require("each"),load=require("load-script");module.exports=Provider.extend({name:"LiveChat",key:"license",defaults:{license:null},initialize:function(options,ready){window.__lc={license:options.license};load("//cdn.livechatinc.com/tracking.js",ready)},identify:function(userId,traits){if(!window.LC_API)return;var variables=[];if(userId)variables.push({name:"User ID",value:userId});if(traits){each(traits,function(key,value){variables.push({name:key,value:value})})}window.LC_API.set_custom_variables(variables)}})});require.register("analytics/src/providers/lytics.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Lytics",key:"cid",defaults:{cid:null},initialize:function(options,ready){window.jstag=function(){var t={_q:[],_c:{cid:options.cid,url:"//c.lytics.io"},ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();load("//c.lytics.io/static/io.min.js");ready()},identify:function(userId,traits){traits._uid=userId;window.jstag.send(traits)},track:function(event,properties){properties._e=event;window.jstag.send(properties)},pageview:function(url){window.jstag.send()}})});require.register("analytics/src/providers/mixpanel.js",function(exports,require,module){var Provider=require("../provider"),alias=require("alias"),isEmail=require("is-email"),load=require("load-script");module.exports=Provider.extend({name:"Mixpanel",key:"token",defaults:{nameTag:true,people:false,token:null,pageview:false,initialPageview:false,cookieName:null},initialize:function(options,ready){!function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2;load("//cdn.mxpnl.com/libs/mixpanel-2.2.min.js",ready)}(document,window.mixpanel||[]);options.cookie_name=options.cookieName;window.mixpanel.init(options.token,options);if(options.initialPageview)this.pageview()},identify:function(userId,traits){alias(traits,{created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"});if(userId){window.mixpanel.identify(userId);if(this.options.nameTag)window.mixpanel.name_tag(traits&&traits.$email||userId)}if(traits){window.mixpanel.register(traits);if(this.options.people)window.mixpanel.people.set(traits)}},track:function(event,properties){window.mixpanel.track(event,properties);if(properties&&properties.revenue&&this.options.people){window.mixpanel.people.track_charge(properties.revenue)}},pageview:function(url){window.mixpanel.track_pageview(url);if(!this.options.pageview)return;var properties={url:url||document.location.href,name:document.title};this.track("Loaded a Page",properties)},alias:function(newId,originalId){if(window.mixpanel.get_distinct_id&&window.mixpanel.get_distinct_id()===newId)return;if(window.mixpanel.get_property&&window.mixpanel.get_property("$people_distinct_id")===newId)return;window.mixpanel.alias(newId,originalId)}})});require.register("analytics/src/providers/olark.js",function(exports,require,module){var Provider=require("../provider"),isEmail=require("is-email");module.exports=Provider.extend({name:"Olark",key:"siteId",chatting:false,defaults:{siteId:null,identify:true,track:false,pageview:true},initialize:function(options,ready){window.olark||function(c){var f=window,d=document,l=f.location.protocol=="https:"?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){!function(n){f[z][n]=function(){f[z]("call",n,arguments)}}(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(options.siteId);var self=this;window.olark("api.box.onExpand",function(){self.chatting=true});window.olark("api.box.onShrink",function(){self.chatting=false});ready()},identify:function(userId,traits){if(!this.options.identify)return;var email=traits.email,name=traits.name||traits.firstName,phone=traits.phone,nickname=name||email||userId;if(name&&email)nickname+=" ("+email+")";window.olark("api.visitor.updateCustomFields",traits);if(email)window.olark("api.visitor.updateEmailAddress",{emailAddress:email});if(name)window.olark("api.visitor.updateFullName",{fullName:name});if(phone)window.olark("api.visitor.updatePhoneNumber",{phoneNumber:phone});if(nickname)window.olark("api.chat.updateVisitorNickname",{snippet:nickname})},track:function(event,properties){if(!this.options.track||!this.chatting)return;window.olark("api.chat.sendNotificationToOperator",{body:'visitor triggered "'+event+'"'})},pageview:function(url){if(!this.options.pageview||!this.chatting)return;window.olark("api.chat.sendNotificationToOperator",{body:"looking at "+window.location.href})}})});require.register("analytics/src/providers/optimizely.js",function(exports,require,module){var each=require("each"),nextTick=require("next-tick"),Provider=require("../provider");module.exports=Provider.extend({name:"Optimizely",defaults:{variations:true},initialize:function(options,ready,analytics){window.optimizely=window.optimizely||[];if(options.variations){var self=this;nextTick(function(){self.replay()})}ready()},track:function(event,properties){if(properties&&properties.revenue)properties.revenue=properties.revenue*100;window.optimizely.push(["trackEvent",event,properties])},replay:function(){var data=window.optimizely.data;if(!data)return;var experiments=data.experiments,variationNamesMap=data.state.variationNamesMap;var traits={};each(variationNamesMap,function(experimentId,variation){traits["Experiment: "+experiments[experimentId].name]=variation});this.analytics.identify(traits)}})});require.register("analytics/src/providers/perfect-audience.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Perfect Audience",key:"siteId",defaults:{siteId:null},initialize:function(options,ready){window._pa||(window._pa={});load("//tag.perfectaudience.com/serve/"+options.siteId+".js",ready)},track:function(event,properties){window._pa.track(event,properties)}})});require.register("analytics/src/providers/pingdom.js",function(exports,require,module){var date=require("load-date"),Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Pingdom",key:"id",defaults:{id:null},initialize:function(options,ready){window._prum=[["id",options.id],["mark","firstbyte",date.getTime()]];load("//rum-static.pingdom.net/prum.min.js",ready)}})});require.register("analytics/src/providers/preact.js",function(exports,require,module){var Provider=require("../provider"),isEmail=require("is-email"),load=require("load-script");module.exports=Provider.extend({name:"Preact",key:"projectCode",defaults:{projectCode:null},initialize:function(options,ready){var _lnq=window._lnq=window._lnq||[];_lnq.push(["_setCode",options.projectCode]);load("//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js");ready()},identify:function(userId,traits){if(!userId)return;if(traits.created){traits.created_at=Math.floor(traits.created/1e3);delete traits.created
}window._lnq.push(["_setPersonData",{name:traits.name,email:traits.email,uid:userId,properties:traits}])},group:function(groupId,properties){if(!groupId)return;properties.id=groupId;window._lnq.push(["_setAccount",properties])},track:function(event,properties){properties||(properties={});var special={name:event};if(properties.revenue){special.revenue=properties.revenue*100;delete properties.revenue}if(properties.note){special.note=properties.note;delete properties.note}window._lnq.push(["_logEvent",special,properties])}})});require.register("analytics/src/providers/qualaroo.js",function(exports,require,module){var Provider=require("../provider"),isEmail=require("is-email"),load=require("load-script");module.exports=Provider.extend({name:"Qualaroo",defaults:{customerId:null,siteToken:null,track:false},initialize:function(options,ready){window._kiq=window._kiq||[];load("//s3.amazonaws.com/ki.js/"+options.customerId+"/"+options.siteToken+".js");ready()},identify:function(userId,traits){var identity=traits.email||userId;if(identity)window._kiq.push(["identify",identity]);if(traits)window._kiq.push(["set",traits])},track:function(event,properties){if(!this.options.track)return;var traits={};traits["Triggered: "+event]=true;this.identify(null,traits)}})});require.register("analytics/src/providers/quantcast.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Quantcast",key:"pCode",defaults:{pCode:null},initialize:function(options,ready){window._qevents=window._qevents||[];window._qevents.push({qacct:options.pCode});load({http:"http://edge.quantserve.com/quant.js",https:"https://secure.quantserve.com/quant.js"},ready)}})});require.register("analytics/src/providers/sentry.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script");module.exports=Provider.extend({name:"Sentry",key:"config",defaults:{config:null},initialize:function(options,ready){load("//d3nslu0hdya83q.cloudfront.net/dist/1.0/raven.min.js",function(){window.Raven.config(options.config).install();ready()})},identify:function(userId,traits){traits.id=userId;window.Raven.setUser(traits)},log:function(error,properties){window.Raven.captureException(error,properties)}})});require.register("analytics/src/providers/snapengage.js",function(exports,require,module){var Provider=require("../provider"),isEmail=require("is-email"),load=require("load-script");module.exports=Provider.extend({name:"SnapEngage",key:"apiKey",defaults:{apiKey:null},initialize:function(options,ready){load("//commondatastorage.googleapis.com/code.snapengage.com/js/"+options.apiKey+".js",ready)},identify:function(userId,traits,options){if(!traits.email)return;window.SnapABug.setUserEmail(traits.email)}})});require.register("analytics/src/providers/usercycle.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script"),user=require("../user");module.exports=Provider.extend({name:"USERcycle",key:"key",defaults:{key:null},initialize:function(options,ready){window._uc=window._uc||[];window._uc.push(["_key",options.key]);load("//api.usercycle.com/javascripts/track.js");ready()},identify:function(userId,traits){if(userId)window._uc.push(["uid",userId]);window._uc.push(["action","came_back",traits])},track:function(event,properties){window._uc.push(["action",event,properties])}})});require.register("analytics/src/providers/userfox.js",function(exports,require,module){var Provider=require("../provider"),extend=require("extend"),load=require("load-script"),isEmail=require("is-email");module.exports=Provider.extend({name:"userfox",key:"clientId",defaults:{clientId:null},initialize:function(options,ready){window._ufq=window._ufq||[];load("//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js");ready()},identify:function(userId,traits){if(!traits.email)return;window._ufq.push(["init",{clientId:this.options.clientId,email:traits.email}]);if(traits.created){traits.signup_date=(traits.created.getTime()/1e3).toString();delete traits.created;window._ufq.push(["track",traits])}}})});require.register("analytics/src/providers/uservoice.js",function(exports,require,module){var Provider=require("../provider"),load=require("load-script"),alias=require("alias"),clone=require("clone");module.exports=Provider.extend({name:"UserVoice",defaults:{widgetId:null,forumId:null,showTab:true,mode:"full",primaryColor:"#cc6d00",linkColor:"#007dbf",defaultMode:"support",tabLabel:"Feedback & Support",tabColor:"#cc6d00",tabPosition:"middle-right",tabInverted:false},initialize:function(options,ready){window.UserVoice=window.UserVoice||[];load("//widget.uservoice.com/"+options.widgetId+".js",ready);var optionsClone=clone(options);alias(optionsClone,{forumId:"forum_id",primaryColor:"primary_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabColor:"tab_color",tabPosition:"tab_position",tabInverted:"tab_inverted"});window.showClassicWidget=function(showWhat){window.UserVoice.push([showWhat||"showLightbox","classic_widget",optionsClone])};if(options.showTab){window.showClassicWidget("showTab")}},identify:function(userId,traits){traits.id=userId;window.UserVoice.push(["setCustomFields",traits])}})});require.register("analytics/src/providers/vero.js",function(exports,require,module){var Provider=require("../provider"),isEmail=require("is-email"),load=require("load-script");module.exports=Provider.extend({name:"Vero",key:"apiKey",defaults:{apiKey:null},initialize:function(options,ready){window._veroq=window._veroq||[];window._veroq.push(["init",{api_key:options.apiKey}]);load("//d3qxef4rp70elm.cloudfront.net/m.js");ready()},identify:function(userId,traits){if(!userId||!traits.email)return;traits.id=userId;window._veroq.push(["user",traits])},track:function(event,properties){window._veroq.push(["track",event,properties])}})});require.register("analytics/src/providers/visual-website-optimizer.js",function(exports,require,module){var each=require("each"),inherit=require("inherit"),nextTick=require("next-tick"),Provider=require("../provider");module.exports=VWO;function VWO(){Provider.apply(this,arguments)}inherit(VWO,Provider);VWO.prototype.name="Visual Website Optimizer";VWO.prototype.defaults={replay:true};VWO.prototype.initialize=function(options,ready){if(options.replay)this.replay();ready()};VWO.prototype.replay=function(){var analytics=this.analytics;nextTick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(callback){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return callback();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});callback(null,data)})}function enqueue(fn){window._vis_opt_queue||(window._vis_opt_queue=[]);window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}});require.register("analytics/src/providers/woopra.js",function(exports,require,module){var Provider=require("../provider"),each=require("each"),extend=require("extend"),isEmail=require("is-email"),load=require("load-script"),type=require("type"),user=require("../user");module.exports=Provider.extend({name:"Woopra",key:"domain",defaults:{domain:null},initialize:function(options,ready){var self=this;window.woopraReady=function(tracker){tracker.setDomain(self.options.domain);tracker.setIdleTimeout(3e5);var userId=user.id(),traits=user.traits();addTraits(userId,traits,tracker);tracker.track();ready();return false};load("//static.woopra.com/js/woopra.js")},identify:function(userId,traits){if(!window.woopraTracker)return;addTraits(userId,traits,window.woopraTracker)},track:function(event,properties){if(!window.woopraTracker)return;properties||(properties={});properties.name=event;window.woopraTracker.pushEvent(properties)}});function addTraits(userId,traits,tracker){if(userId)traits.id=userId;each(traits,function(key,value){if("string"===type(value))tracker.addVisitorProperty(key,value)})}});require.alias("avetisk-defaults/index.js","analytics/deps/defaults/index.js");require.alias("avetisk-defaults/index.js","defaults/index.js");require.alias("component-clone/index.js","analytics/deps/clone/index.js");require.alias("component-clone/index.js","clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-cookie/index.js","analytics/deps/cookie/index.js");require.alias("component-cookie/index.js","cookie/index.js");require.alias("component-each/index.js","analytics/deps/each/index.js");require.alias("component-each/index.js","each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("component-event/index.js","analytics/deps/event/index.js");require.alias("component-event/index.js","event/index.js");require.alias("component-inherit/index.js","analytics/deps/inherit/index.js");require.alias("component-inherit/index.js","inherit/index.js");require.alias("component-object/index.js","analytics/deps/object/index.js");require.alias("component-object/index.js","object/index.js");require.alias("component-querystring/index.js","analytics/deps/querystring/index.js");require.alias("component-querystring/index.js","querystring/index.js");require.alias("component-trim/index.js","component-querystring/deps/trim/index.js");require.alias("component-type/index.js","analytics/deps/type/index.js");require.alias("component-type/index.js","type/index.js");require.alias("component-url/index.js","analytics/deps/url/index.js");require.alias("component-url/index.js","url/index.js");require.alias("segmentio-after/index.js","analytics/deps/after/index.js");require.alias("segmentio-after/index.js","after/index.js");require.alias("segmentio-alias/index.js","analytics/deps/alias/index.js");require.alias("segmentio-alias/index.js","alias/index.js");require.alias("segmentio-bind-all/index.js","analytics/deps/bind-all/index.js");require.alias("segmentio-bind-all/index.js","analytics/deps/bind-all/index.js");require.alias("segmentio-bind-all/index.js","bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("segmentio-bind-all/index.js","segmentio-bind-all/index.js");require.alias("segmentio-canonical/index.js","analytics/deps/canonical/index.js");require.alias("segmentio-canonical/index.js","canonical/index.js");require.alias("segmentio-extend/index.js","analytics/deps/extend/index.js");require.alias("segmentio-extend/index.js","extend/index.js");require.alias("segmentio-is-email/index.js","analytics/deps/is-email/index.js");require.alias("segmentio-is-email/index.js","is-email/index.js");require.alias("segmentio-is-meta/index.js","analytics/deps/is-meta/index.js");require.alias("segmentio-is-meta/index.js","is-meta/index.js");require.alias("segmentio-json/index.js","analytics/deps/json/index.js");require.alias("segmentio-json/index.js","json/index.js");require.alias("component-json-fallback/index.js","segmentio-json/deps/json-fallback/index.js");require.alias("segmentio-load-date/index.js","analytics/deps/load-date/index.js");require.alias("segmentio-load-date/index.js","load-date/index.js");require.alias("segmentio-load-script/index.js","analytics/deps/load-script/index.js");require.alias("segmentio-load-script/index.js","load-script/index.js");require.alias("component-type/index.js","segmentio-load-script/deps/type/index.js");require.alias("segmentio-new-date/index.js","analytics/deps/new-date/index.js");require.alias("segmentio-new-date/index.js","new-date/index.js");require.alias("segmentio-type/index.js","segmentio-new-date/deps/type/index.js");require.alias("segmentio-on-body/index.js","analytics/deps/on-body/index.js");require.alias("segmentio-on-body/index.js","on-body/index.js");require.alias("component-each/index.js","segmentio-on-body/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("segmentio-store.js/store.js","analytics/deps/store/store.js");require.alias("segmentio-store.js/store.js","analytics/deps/store/index.js");require.alias("segmentio-store.js/store.js","store/index.js");require.alias("segmentio-json/index.js","segmentio-store.js/deps/json/index.js");require.alias("component-json-fallback/index.js","segmentio-json/deps/json-fallback/index.js");require.alias("segmentio-store.js/store.js","segmentio-store.js/index.js");require.alias("segmentio-top-domain/index.js","analytics/deps/top-domain/index.js");require.alias("segmentio-top-domain/index.js","analytics/deps/top-domain/index.js");require.alias("segmentio-top-domain/index.js","top-domain/index.js");require.alias("component-url/index.js","segmentio-top-domain/deps/url/index.js");require.alias("segmentio-top-domain/index.js","segmentio-top-domain/index.js");require.alias("timoxley-next-tick/index.js","analytics/deps/next-tick/index.js");require.alias("timoxley-next-tick/index.js","next-tick/index.js");require.alias("yields-prevent/index.js","analytics/deps/prevent/index.js");require.alias("yields-prevent/index.js","prevent/index.js");require.alias("analytics/src/index.js","analytics/index.js");if(typeof exports=="object"){module.exports=require("analytics")}else if(typeof define=="function"&&define.amd){define(function(){return require("analytics")})}else{this["analytics"]=require("analytics")}}(); |
app/javascript/mastodon/components/short_number.js | masto-donte-com-br/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { toShortNumber, pluralReady, DECIMAL_UNITS } from '../utils/numbers';
import { FormattedMessage, FormattedNumber } from 'react-intl';
// @ts-check
/**
* @callback ShortNumberRenderer
* @param {JSX.Element} displayNumber Number to display
* @param {number} pluralReady Number used for pluralization
* @returns {JSX.Element} Final render of number
*/
/**
* @typedef {object} ShortNumberProps
* @property {number} value Number to display in short variant
* @property {ShortNumberRenderer} [renderer]
* Custom renderer for numbers, provided as a prop. If another renderer
* passed as a child of this component, this prop won't be used.
* @property {ShortNumberRenderer} [children]
* Custom renderer for numbers, provided as a child. If another renderer
* passed as a prop of this component, this one will be used instead.
*/
/**
* Component that renders short big number to a shorter version
*
* @param {ShortNumberProps} param0 Props for the component
* @returns {JSX.Element} Rendered number
*/
function ShortNumber({ value, renderer, children }) {
const shortNumber = toShortNumber(value);
const [, division] = shortNumber;
// eslint-disable-next-line eqeqeq
if (children != null && renderer != null) {
console.warn('Both renderer prop and renderer as a child provided. This is a mistake and you really should fix that. Only renderer passed as a child will be used.');
}
// eslint-disable-next-line eqeqeq
const customRenderer = children != null ? children : renderer;
const displayNumber = <ShortNumberCounter value={shortNumber} />;
// eslint-disable-next-line eqeqeq
return customRenderer != null
? customRenderer(displayNumber, pluralReady(value, division))
: displayNumber;
}
ShortNumber.propTypes = {
value: PropTypes.number.isRequired,
renderer: PropTypes.func,
children: PropTypes.func,
};
/**
* @typedef {object} ShortNumberCounterProps
* @property {import('../utils/number').ShortNumber} value Short number
*/
/**
* Renders short number into corresponding localizable react fragment
*
* @param {ShortNumberCounterProps} param0 Props for the component
* @returns {JSX.Element} FormattedMessage ready to be embedded in code
*/
function ShortNumberCounter({ value }) {
const [rawNumber, unit, maxFractionDigits = 0] = value;
const count = (
<FormattedNumber
value={rawNumber}
maximumFractionDigits={maxFractionDigits}
/>
);
let values = { count, rawNumber };
switch (unit) {
case DECIMAL_UNITS.THOUSAND: {
return (
<FormattedMessage
id='units.short.thousand'
defaultMessage='{count}K'
values={values}
/>
);
}
case DECIMAL_UNITS.MILLION: {
return (
<FormattedMessage
id='units.short.million'
defaultMessage='{count}M'
values={values}
/>
);
}
case DECIMAL_UNITS.BILLION: {
return (
<FormattedMessage
id='units.short.billion'
defaultMessage='{count}B'
values={values}
/>
);
}
// Not sure if we should go farther - @Sasha-Sorokin
default: return count;
}
}
ShortNumberCounter.propTypes = {
value: PropTypes.arrayOf(PropTypes.number),
};
export default React.memo(ShortNumber);
|
src/components/forms/Connect.js | mBeierl/Better-Twitch-Chat | import React from 'react';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import { Card, CardActions, CardTitle, CardText } from 'material-ui/Card';
const Connect = props =>
<Card className="container">
<CardTitle title="Connect to a Twitch-Channel" />
<CardText>
<TextField
hintText="Jonsandman"
floatingLabelText="Channel-Name"
onChange={props.onChannelNameChanged}
/>
</CardText>
<CardActions>
<FlatButton label="Connect" primary onTouchTap={props.onConnectClicked} />
</CardActions>
</Card>;
export default Connect;
|
ajax/libs/jqwidgets/12.2.1/jqwidgets-react-tsx/jqxformattedinput/react_jqxformattedinput.umd.js | cdnjs/cdnjs | require('../../jqwidgets/jqxcore');
require('../../jqwidgets/jqxformattedinput');
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(factory((global.react_jqxformattedinput = {}),global.React));
}(this, (function (exports,React) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var JqxFormattedInput = /** @class */ (function (_super) {
__extends(JqxFormattedInput, _super);
function JqxFormattedInput(props) {
var _this = _super.call(this, props) || this;
/* tslint:disable:variable-name */
_this._jqx = JQXLite;
_this._id = 'JqxFormattedInput' + _this._jqx.generateID();
_this._componentSelector = '#' + _this._id;
_this.state = { lastProps: props };
return _this;
}
JqxFormattedInput.getDerivedStateFromProps = function (props, state) {
if (!Object.is) {
Object.is = function (x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
}
else {
return x !== x && y !== y;
}
};
}
var areEqual = Object.is(props, state.lastProps);
if (!areEqual) {
var newState = { lastProps: props };
return newState;
}
return null;
};
JqxFormattedInput.prototype.componentDidMount = function () {
var widgetOptions = this._manageProps();
this._jqx(this._componentSelector).jqxFormattedInput(widgetOptions);
this._wireEvents();
};
JqxFormattedInput.prototype.componentDidUpdate = function () {
var widgetOptions = this._manageProps();
this.setOptions(widgetOptions);
this._wireEvents();
};
JqxFormattedInput.prototype.render = function () {
return (React.createElement("div", { id: this._id },
!this.props.rtl && React.createElement("input", { type: 'text' }),
this.props.spinButtons && React.createElement("div", null),
this.props.dropDown && React.createElement("div", null),
this.props.rtl && React.createElement("input", { type: 'text' })));
};
JqxFormattedInput.prototype.setOptions = function (options) {
this._jqx(this._componentSelector).jqxFormattedInput(options);
};
JqxFormattedInput.prototype.getOptions = function (option) {
return this._jqx(this._componentSelector).jqxFormattedInput(option);
};
JqxFormattedInput.prototype.close = function () {
this._jqx(this._componentSelector).jqxFormattedInput('close');
};
JqxFormattedInput.prototype.destroy = function () {
this._jqx(this._componentSelector).jqxFormattedInput('destroy');
};
JqxFormattedInput.prototype.focus = function () {
this._jqx(this._componentSelector).jqxFormattedInput('focus');
};
JqxFormattedInput.prototype.open = function () {
this._jqx(this._componentSelector).jqxFormattedInput('open');
};
JqxFormattedInput.prototype.renderWidget = function () {
this._jqx(this._componentSelector).jqxFormattedInput('render');
};
JqxFormattedInput.prototype.refresh = function () {
this._jqx(this._componentSelector).jqxFormattedInput('refresh');
};
JqxFormattedInput.prototype.selectAll = function () {
this._jqx(this._componentSelector).jqxFormattedInput('selectAll');
};
JqxFormattedInput.prototype.selectFirst = function () {
this._jqx(this._componentSelector).jqxFormattedInput('selectFirst');
};
JqxFormattedInput.prototype.selectLast = function () {
this._jqx(this._componentSelector).jqxFormattedInput('selectLast');
};
JqxFormattedInput.prototype.val = function (value) {
if (value) {
this._jqx(this._componentSelector).jqxFormattedInput('val', value);
}
else {
return this._jqx(this._componentSelector).jqxFormattedInput('val');
}
};
JqxFormattedInput.prototype._manageProps = function () {
var widgetProps = ['disabled', 'decimalNotation', 'dropDown', 'dropDownWidth', 'height', 'min', 'max', 'placeHolder', 'popupZIndex', 'roundedCorners', 'rtl', 'radix', 'spinButtons', 'spinButtonsStep', 'template', 'theme', 'upperCase', 'value', 'width'];
var options = {};
for (var prop in this.props) {
if (widgetProps.indexOf(prop) !== -1) {
options[prop] = this.props[prop];
}
}
return options;
};
JqxFormattedInput.prototype._wireEvents = function () {
for (var prop in this.props) {
if (prop.indexOf('on') === 0) {
var originalEventName = prop.slice(2);
originalEventName = originalEventName.charAt(0).toLowerCase() + originalEventName.slice(1);
this._jqx(this._componentSelector).off(originalEventName);
this._jqx(this._componentSelector).on(originalEventName, this.props[prop]);
}
}
};
return JqxFormattedInput;
}(React.PureComponent));
var jqx = window.jqx;
var JQXLite = window.JQXLite;
exports.default = JqxFormattedInput;
exports.jqx = jqx;
exports.JQXLite = JQXLite;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
ajax/libs/yui/3.11.0/scrollview-base/scrollview-base-debug.js | mayur404/cdnjs | YUI.add('scrollview-base', function (Y, NAME) {
/**
* The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators
*
* @module scrollview
* @submodule scrollview-base
*/
// Local vars
var getClassName = Y.ClassNameManager.getClassName,
DOCUMENT = Y.config.doc,
IE = Y.UA.ie,
NATIVE_TRANSITIONS = Y.Transition.useNative,
vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated
SCROLLVIEW = 'scrollview',
CLASS_NAMES = {
vertical: getClassName(SCROLLVIEW, 'vert'),
horizontal: getClassName(SCROLLVIEW, 'horiz')
},
EV_SCROLL_END = 'scrollEnd',
FLICK = 'flick',
DRAG = 'drag',
MOUSEWHEEL = 'mousewheel',
UI = 'ui',
TOP = 'top',
LEFT = 'left',
PX = 'px',
AXIS = 'axis',
SCROLL_Y = 'scrollY',
SCROLL_X = 'scrollX',
BOUNCE = 'bounce',
DISABLED = 'disabled',
DECELERATION = 'deceleration',
DIM_X = 'x',
DIM_Y = 'y',
BOUNDING_BOX = 'boundingBox',
CONTENT_BOX = 'contentBox',
GESTURE_MOVE = 'gesturemove',
START = 'start',
END = 'end',
EMPTY = '',
ZERO = '0s',
SNAP_DURATION = 'snapDuration',
SNAP_EASING = 'snapEasing',
EASING = 'easing',
FRAME_DURATION = 'frameDuration',
BOUNCE_RANGE = 'bounceRange',
_constrain = function (val, min, max) {
return Math.min(Math.max(val, min), max);
};
/**
* ScrollView provides a scrollable widget, supporting flick gestures,
* across both touch and mouse based devices.
*
* @class ScrollView
* @param config {Object} Object literal with initial attribute values
* @extends Widget
* @constructor
*/
function ScrollView() {
ScrollView.superclass.constructor.apply(this, arguments);
}
Y.ScrollView = Y.extend(ScrollView, Y.Widget, {
// *** Y.ScrollView prototype
/**
* Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit.
* Used by the _transform method.
*
* @property _forceHWTransforms
* @type boolean
* @protected
*/
_forceHWTransforms: Y.UA.webkit ? true : false,
/**
* <p>Used to control whether or not ScrollView's internal
* gesturemovestart, gesturemove and gesturemoveend
* event listeners should preventDefault. The value is an
* object, with "start", "move" and "end" properties used to
* specify which events should preventDefault and which shouldn't:</p>
*
* <pre>
* {
* start: false,
* move: true,
* end: false
* }
* </pre>
*
* <p>The default values are set up in order to prevent panning,
* on touch devices, while allowing click listeners on elements inside
* the ScrollView to be notified as expected.</p>
*
* @property _prevent
* @type Object
* @protected
*/
_prevent: {
start: false,
move: true,
end: false
},
/**
* Contains the distance (postive or negative) in pixels by which
* the scrollview was last scrolled. This is useful when setting up
* click listeners on the scrollview content, which on mouse based
* devices are always fired, even after a drag/flick.
*
* <p>Touch based devices don't currently fire a click event,
* if the finger has been moved (beyond a threshold) so this
* check isn't required, if working in a purely touch based environment</p>
*
* @property lastScrolledAmt
* @type Number
* @public
* @default 0
*/
lastScrolledAmt: 0,
/**
* Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis
*
* @property _minScrollX
* @type number
* @protected
*/
_minScrollX: null,
/**
* Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis
*
* @property _maxScrollX
* @type number
* @protected
*/
_maxScrollX: null,
/**
* Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis
*
* @property _minScrollY
* @type number
* @protected
*/
_minScrollY: null,
/**
* Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis
*
* @property _maxScrollY
* @type number
* @protected
*/
_maxScrollY: null,
/**
* Designated initializer
*
* @method initializer
* @param {config} Configuration object for the plugin
*/
initializer: function () {
var sv = this;
// Cache these values, since they aren't going to change.
sv._bb = sv.get(BOUNDING_BOX);
sv._cb = sv.get(CONTENT_BOX);
// Cache some attributes
sv._cAxis = sv.get(AXIS);
sv._cBounce = sv.get(BOUNCE);
sv._cBounceRange = sv.get(BOUNCE_RANGE);
sv._cDeceleration = sv.get(DECELERATION);
sv._cFrameDuration = sv.get(FRAME_DURATION);
},
/**
* bindUI implementation
*
* Hooks up events for the widget
* @method bindUI
*/
bindUI: function () {
var sv = this;
// Bind interaction listers
sv._bindFlick(sv.get(FLICK));
sv._bindDrag(sv.get(DRAG));
sv._bindMousewheel(true);
// Bind change events
sv._bindAttrs();
// IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release.
if (IE) {
sv._fixIESelect(sv._bb, sv._cb);
}
// Set any deprecated static properties
if (ScrollView.SNAP_DURATION) {
sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION);
}
if (ScrollView.SNAP_EASING) {
sv.set(SNAP_EASING, ScrollView.SNAP_EASING);
}
if (ScrollView.EASING) {
sv.set(EASING, ScrollView.EASING);
}
if (ScrollView.FRAME_STEP) {
sv.set(FRAME_DURATION, ScrollView.FRAME_STEP);
}
if (ScrollView.BOUNCE_RANGE) {
sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE);
}
// Recalculate dimension properties
// TODO: This should be throttled.
// Y.one(WINDOW).after('resize', sv._afterDimChange, sv);
},
/**
* Bind event listeners
*
* @method _bindAttrs
* @private
*/
_bindAttrs: function () {
var sv = this,
scrollChangeHandler = sv._afterScrollChange,
dimChangeHandler = sv._afterDimChange;
// Bind any change event listeners
sv.after({
'scrollEnd': sv._afterScrollEnd,
'disabledChange': sv._afterDisabledChange,
'flickChange': sv._afterFlickChange,
'dragChange': sv._afterDragChange,
'axisChange': sv._afterAxisChange,
'scrollYChange': scrollChangeHandler,
'scrollXChange': scrollChangeHandler,
'heightChange': dimChangeHandler,
'widthChange': dimChangeHandler
});
},
/**
* Bind (or unbind) gesture move listeners required for drag support
*
* @method _bindDrag
* @param drag {boolean} If true, the method binds listener to enable
* drag (gesturemovestart). If false, the method unbinds gesturemove
* listeners for drag support.
* @private
*/
_bindDrag: function (drag) {
var sv = this,
bb = sv._bb;
// Unbind any previous 'drag' listeners
bb.detach(DRAG + '|*');
if (drag) {
bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv));
}
},
/**
* Bind (or unbind) flick listeners.
*
* @method _bindFlick
* @param flick {Object|boolean} If truthy, the method binds listeners for
* flick support. If false, the method unbinds flick listeners.
* @private
*/
_bindFlick: function (flick) {
var sv = this,
bb = sv._bb;
// Unbind any previous 'flick' listeners
bb.detach(FLICK + '|*');
if (flick) {
bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick);
// Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick
sv._bindDrag(sv.get(DRAG));
}
},
/**
* Bind (or unbind) mousewheel listeners.
*
* @method _bindMousewheel
* @param mousewheel {Object|boolean} If truthy, the method binds listeners for
* mousewheel support. If false, the method unbinds mousewheel listeners.
* @private
*/
_bindMousewheel: function (mousewheel) {
var sv = this,
bb = sv._bb;
// Unbind any previous 'mousewheel' listeners
// TODO: This doesn't actually appear to work properly. Fix. #2532743
bb.detach(MOUSEWHEEL + '|*');
// Only enable for vertical scrollviews
if (mousewheel) {
// Bound to document, because that's where mousewheel events fire off of.
Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv));
}
},
/**
* syncUI implementation.
*
* Update the scroll position, based on the current value of scrollX/scrollY.
*
* @method syncUI
*/
syncUI: function () {
var sv = this,
scrollDims = sv._getScrollDims(),
width = scrollDims.offsetWidth,
height = scrollDims.offsetHeight,
scrollWidth = scrollDims.scrollWidth,
scrollHeight = scrollDims.scrollHeight;
// If the axis is undefined, auto-calculate it
if (sv._cAxis === undefined) {
// This should only ever be run once (for now).
// In the future SV might post-load axis changes
sv._cAxis = {
x: (scrollWidth > width),
y: (scrollHeight > height)
};
sv._set(AXIS, sv._cAxis);
}
// get text direction on or inherited by scrollview node
sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl');
// Cache the disabled value
sv._cDisabled = sv.get(DISABLED);
// Run this to set initial values
sv._uiDimensionsChange();
// If we're out-of-bounds, snap back.
if (sv._isOutOfBounds()) {
sv._snapBack();
}
},
/**
* Utility method to obtain widget dimensions
*
* @method _getScrollDims
* @return {Object} The offsetWidth, offsetHeight, scrollWidth and
* scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth,
* scrollHeight]
* @private
*/
_getScrollDims: function () {
var sv = this,
cb = sv._cb,
bb = sv._bb,
TRANS = ScrollView._TRANSITION,
// Ideally using CSSMatrix - don't think we have it normalized yet though.
// origX = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).e,
// origY = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).f,
origX = sv.get(SCROLL_X),
origY = sv.get(SCROLL_Y),
origHWTransform,
dims;
// TODO: Is this OK? Just in case it's called 'during' a transition.
if (NATIVE_TRANSITIONS) {
cb.setStyle(TRANS.DURATION, ZERO);
cb.setStyle(TRANS.PROPERTY, EMPTY);
}
origHWTransform = sv._forceHWTransforms;
sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac.
sv._moveTo(cb, 0, 0);
dims = {
'offsetWidth': bb.get('offsetWidth'),
'offsetHeight': bb.get('offsetHeight'),
'scrollWidth': bb.get('scrollWidth'),
'scrollHeight': bb.get('scrollHeight')
};
sv._moveTo(cb, -(origX), -(origY));
sv._forceHWTransforms = origHWTransform;
return dims;
},
/**
* This method gets invoked whenever the height or width attributes change,
* allowing us to determine which scrolling axes need to be enabled.
*
* @method _uiDimensionsChange
* @protected
*/
_uiDimensionsChange: function () {
var sv = this,
bb = sv._bb,
scrollDims = sv._getScrollDims(),
width = scrollDims.offsetWidth,
height = scrollDims.offsetHeight,
scrollWidth = scrollDims.scrollWidth,
scrollHeight = scrollDims.scrollHeight,
rtl = sv.rtl,
svAxis = sv._cAxis,
minScrollX = (rtl ? Math.min(0, -(scrollWidth - width)) : 0),
maxScrollX = (rtl ? 0 : Math.max(0, scrollWidth - width)),
minScrollY = 0,
maxScrollY = Math.max(0, scrollHeight - height);
if (svAxis && svAxis.x) {
bb.addClass(CLASS_NAMES.horizontal);
}
if (svAxis && svAxis.y) {
bb.addClass(CLASS_NAMES.vertical);
}
sv._setBounds({
minScrollX: minScrollX,
maxScrollX: maxScrollX,
minScrollY: minScrollY,
maxScrollY: maxScrollY
});
},
/**
* Set the bounding dimensions of the ScrollView
*
* @method _setBounds
* @protected
* @param bounds {Object} [duration] ms of the scroll animation. (default is 0)
* @param {Number} [bounds.minScrollX] The minimum scroll X value
* @param {Number} [bounds.maxScrollX] The maximum scroll X value
* @param {Number} [bounds.minScrollY] The minimum scroll Y value
* @param {Number} [bounds.maxScrollY] The maximum scroll Y value
*/
_setBounds: function (bounds) {
var sv = this;
// TODO: Do a check to log if the bounds are invalid
sv._minScrollX = bounds.minScrollX;
sv._maxScrollX = bounds.maxScrollX;
sv._minScrollY = bounds.minScrollY;
sv._maxScrollY = bounds.maxScrollY;
},
/**
* Get the bounding dimensions of the ScrollView
*
* @method _getBounds
* @protected
*/
_getBounds: function () {
var sv = this;
return {
minScrollX: sv._minScrollX,
maxScrollX: sv._maxScrollX,
minScrollY: sv._minScrollY,
maxScrollY: sv._maxScrollY
};
},
/**
* Scroll the element to a given xy coordinate
*
* @method scrollTo
* @param x {Number} The x-position to scroll to. (null for no movement)
* @param y {Number} The y-position to scroll to. (null for no movement)
* @param {Number} [duration] ms of the scroll animation. (default is 0)
* @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute)
* @param {String} [node] The node to transform. Setting this can be useful in
* dual-axis paginated instances. (default is the instance's contentBox)
*/
scrollTo: function (x, y, duration, easing, node) {
// Check to see if widget is disabled
if (this._cDisabled) {
return;
}
var sv = this,
cb = sv._cb,
TRANS = ScrollView._TRANSITION,
callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this
newX = 0,
newY = 0,
transition = {},
transform;
// default the optional arguments
duration = duration || 0;
easing = easing || sv.get(EASING); // @TODO: Cache this
node = node || cb;
if (x !== null) {
sv.set(SCROLL_X, x, {src:UI});
newX = -(x);
}
if (y !== null) {
sv.set(SCROLL_Y, y, {src:UI});
newY = -(y);
}
transform = sv._transform(newX, newY);
if (NATIVE_TRANSITIONS) {
// ANDROID WORKAROUND - try and stop existing transition, before kicking off new one.
node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY);
}
// Move
if (duration === 0) {
if (NATIVE_TRANSITIONS) {
node.setStyle('transform', transform);
}
else {
// TODO: If both set, batch them in the same update
// Update: Nope, setStyles() just loops through each property and applies it.
if (x !== null) {
node.setStyle(LEFT, newX + PX);
}
if (y !== null) {
node.setStyle(TOP, newY + PX);
}
}
}
// Animate
else {
transition.easing = easing;
transition.duration = duration / 1000;
if (NATIVE_TRANSITIONS) {
transition.transform = transform;
}
else {
transition.left = newX + PX;
transition.top = newY + PX;
}
node.transition(transition, callback);
}
},
/**
* Utility method, to create the translate transform string with the
* x, y translation amounts provided.
*
* @method _transform
* @param {Number} x Number of pixels to translate along the x axis
* @param {Number} y Number of pixels to translate along the y axis
* @private
*/
_transform: function (x, y) {
// TODO: Would we be better off using a Matrix for this?
var prop = 'translate(' + x + 'px, ' + y + 'px)';
if (this._forceHWTransforms) {
prop += ' translateZ(0)';
}
return prop;
},
/**
* Utility method, to move the given element to the given xy position
*
* @method _moveTo
* @param node {Node} The node to move
* @param x {Number} The x-position to move to
* @param y {Number} The y-position to move to
* @private
*/
_moveTo : function(node, x, y) {
if (NATIVE_TRANSITIONS) {
node.setStyle('transform', this._transform(x, y));
} else {
node.setStyle(LEFT, x + PX);
node.setStyle(TOP, y + PX);
}
},
/**
* Content box transition callback
*
* @method _onTransEnd
* @param {Event.Facade} e The event facade
* @private
*/
_onTransEnd: function () {
var sv = this;
// If for some reason we're OOB, snapback
if (sv._isOutOfBounds()) {
sv._snapBack();
}
else {
/**
* Notification event fired at the end of a scroll transition
*
* @event scrollEnd
* @param e {EventFacade} The default event facade.
*/
sv.fire(EV_SCROLL_END);
}
},
/**
* gesturemovestart event handler
*
* @method _onGestureMoveStart
* @param e {Event.Facade} The gesturemovestart event facade
* @private
*/
_onGestureMoveStart: function (e) {
if (this._cDisabled) {
return false;
}
var sv = this,
bb = sv._bb,
currentX = sv.get(SCROLL_X),
currentY = sv.get(SCROLL_Y),
clientX = e.clientX,
clientY = e.clientY;
if (sv._prevent.start) {
e.preventDefault();
}
// if a flick animation is in progress, cancel it
if (sv._flickAnim) {
sv._cancelFlick();
sv._onTransEnd();
}
// Reset lastScrolledAmt
sv.lastScrolledAmt = 0;
// Stores data for this gesture cycle. Cleaned up later
sv._gesture = {
// Will hold the axis value
axis: null,
// The current attribute values
startX: currentX,
startY: currentY,
// The X/Y coordinates where the event began
startClientX: clientX,
startClientY: clientY,
// The X/Y coordinates where the event will end
endClientX: null,
endClientY: null,
// The current delta of the event
deltaX: null,
deltaY: null,
// Will be populated for flicks
flick: null,
// Create some listeners for the rest of the gesture cycle
onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)),
// @TODO: Don't bind gestureMoveEnd if it's a Flick?
onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv))
};
},
/**
* gesturemove event handler
*
* @method _onGestureMove
* @param e {Event.Facade} The gesturemove event facade
* @private
*/
_onGestureMove: function (e) {
var sv = this,
gesture = sv._gesture,
svAxis = sv._cAxis,
svAxisX = svAxis.x,
svAxisY = svAxis.y,
startX = gesture.startX,
startY = gesture.startY,
startClientX = gesture.startClientX,
startClientY = gesture.startClientY,
clientX = e.clientX,
clientY = e.clientY;
if (sv._prevent.move) {
e.preventDefault();
}
gesture.deltaX = startClientX - clientX;
gesture.deltaY = startClientY - clientY;
// Determine if this is a vertical or horizontal movement
// @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent
if (gesture.axis === null) {
gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y;
}
// Move X or Y. @TODO: Move both if dualaxis.
if (gesture.axis === DIM_X && svAxisX) {
sv.set(SCROLL_X, startX + gesture.deltaX);
}
else if (gesture.axis === DIM_Y && svAxisY) {
sv.set(SCROLL_Y, startY + gesture.deltaY);
}
},
/**
* gesturemoveend event handler
*
* @method _onGestureMoveEnd
* @param e {Event.Facade} The gesturemoveend event facade
* @private
*/
_onGestureMoveEnd: function (e) {
var sv = this,
gesture = sv._gesture,
flick = gesture.flick,
clientX = e.clientX,
clientY = e.clientY,
isOOB;
if (sv._prevent.end) {
e.preventDefault();
}
// Store the end X/Y coordinates
gesture.endClientX = clientX;
gesture.endClientY = clientY;
// Cleanup the event handlers
gesture.onGestureMove.detach();
gesture.onGestureMoveEnd.detach();
// If this wasn't a flick, wrap up the gesture cycle
if (!flick) {
// @TODO: Be more intelligent about this. Look at the Flick attribute to see
// if it is safe to assume _flick did or didn't fire.
// Then, the order _flick and _onGestureMoveEnd fire doesn't matter?
// If there was movement (_onGestureMove fired)
if (gesture.deltaX !== null && gesture.deltaY !== null) {
isOOB = sv._isOutOfBounds();
// If we're out-out-bounds, then snapback
if (isOOB) {
sv._snapBack();
}
// Inbounds
else {
// Fire scrollEnd unless this is a paginated instance and the gesture axis is the same as paginator's
// Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit
if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) {
sv._onTransEnd();
}
}
}
}
},
/**
* Execute a flick at the end of a scroll action
*
* @method _flick
* @param e {Event.Facade} The Flick event facade
* @private
*/
_flick: function (e) {
if (this._cDisabled) {
return false;
}
var sv = this,
svAxis = sv._cAxis,
flick = e.flick,
flickAxis = flick.axis,
flickVelocity = flick.velocity,
axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,
startPosition = sv.get(axisAttr);
// Sometimes flick is enabled, but drag is disabled
if (sv._gesture) {
sv._gesture.flick = flick;
}
// Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis
if (svAxis[flickAxis]) {
sv._flickFrame(flickVelocity, flickAxis, startPosition);
}
},
/**
* Execute a single frame in the flick animation
*
* @method _flickFrame
* @param velocity {Number} The velocity of this animated frame
* @param flickAxis {String} The axis on which to animate
* @param startPosition {Number} The starting X/Y point to flick from
* @protected
*/
_flickFrame: function (velocity, flickAxis, startPosition) {
var sv = this,
axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,
bounds = sv._getBounds(),
// Localize cached values
bounce = sv._cBounce,
bounceRange = sv._cBounceRange,
deceleration = sv._cDeceleration,
frameDuration = sv._cFrameDuration,
// Calculate
newVelocity = velocity * deceleration,
newPosition = startPosition - (frameDuration * newVelocity),
// Some convinience conditions
min = flickAxis === DIM_X ? bounds.minScrollX : bounds.minScrollY,
max = flickAxis === DIM_X ? bounds.maxScrollX : bounds.maxScrollY,
belowMin = (newPosition < min),
belowMax = (newPosition < max),
aboveMin = (newPosition > min),
aboveMax = (newPosition > max),
belowMinRange = (newPosition < (min - bounceRange)),
withinMinRange = (belowMin && (newPosition > (min - bounceRange))),
withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))),
aboveMaxRange = (newPosition > (max + bounceRange)),
tooSlow;
// If we're within the range but outside min/max, dampen the velocity
if (withinMinRange || withinMaxRange) {
newVelocity *= bounce;
}
// Is the velocity too slow to bother?
tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015);
// If the velocity is too slow or we're outside the range
if (tooSlow || belowMinRange || aboveMaxRange) {
// Cancel and delete sv._flickAnim
if (sv._flickAnim) {
sv._cancelFlick();
}
// If we're inside the scroll area, just end
if (aboveMin && belowMax) {
sv._onTransEnd();
}
// We're outside the scroll area, so we need to snap back
else {
sv._snapBack();
}
}
// Otherwise, animate to the next frame
else {
// @TODO: maybe use requestAnimationFrame instead
sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]);
sv.set(axisAttr, newPosition);
}
},
_cancelFlick: function () {
var sv = this;
if (sv._flickAnim) {
// Cancel the flick (if it exists)
sv._flickAnim.cancel();
// Also delete it, otherwise _onGestureMoveStart will think we're still flicking
delete sv._flickAnim;
}
},
/**
* Handle mousewheel events on the widget
*
* @method _mousewheel
* @param e {Event.Facade} The mousewheel event facade
* @private
*/
_mousewheel: function (e) {
var sv = this,
scrollY = sv.get(SCROLL_Y),
bounds = sv._getBounds(),
bb = sv._bb,
scrollOffset = 10, // 10px
isForward = (e.wheelDelta > 0),
scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset);
scrollToY = _constrain(scrollToY, bounds.minScrollY, bounds.maxScrollY);
// Because Mousewheel events fire off 'document', every ScrollView widget will react
// to any mousewheel anywhere on the page. This check will ensure that the mouse is currently
// over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis,
// becuase otherwise the 'prevent' will block page scrolling.
if (bb.contains(e.target) && sv._cAxis[DIM_Y]) {
// Reset lastScrolledAmt
sv.lastScrolledAmt = 0;
// Jump to the new offset
sv.set(SCROLL_Y, scrollToY);
// if we have scrollbars plugin, update & set the flash timer on the scrollbar
// @TODO: This probably shouldn't be in this module
if (sv.scrollbars) {
// @TODO: The scrollbars should handle this themselves
sv.scrollbars._update();
sv.scrollbars.flash();
// or just this
// sv.scrollbars._hostDimensionsChange();
}
// Fire the 'scrollEnd' event
sv._onTransEnd();
// prevent browser default behavior on mouse scroll
e.preventDefault();
}
},
/**
* Checks to see the current scrollX/scrollY position beyond the min/max boundary
*
* @method _isOutOfBounds
* @param x {Number} [optional] The X position to check
* @param y {Number} [optional] The Y position to check
* @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false)
* @private
*/
_isOutOfBounds: function (x, y) {
var sv = this,
svAxis = sv._cAxis,
svAxisX = svAxis.x,
svAxisY = svAxis.y,
currentX = x || sv.get(SCROLL_X),
currentY = y || sv.get(SCROLL_Y),
bounds = sv._getBounds(),
minX = bounds.minScrollX,
minY = bounds.minScrollY,
maxX = bounds.maxScrollX,
maxY = bounds.maxScrollY;
return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY));
},
/**
* Bounces back
* @TODO: Should be more generalized and support both X and Y detection
*
* @method _snapBack
* @private
*/
_snapBack: function () {
var sv = this,
currentX = sv.get(SCROLL_X),
currentY = sv.get(SCROLL_Y),
bounds = sv._getBounds(),
minX = bounds.minScrollX,
minY = bounds.minScrollY,
maxX = bounds.maxScrollX,
maxY = bounds.maxScrollY,
newY = _constrain(currentY, minY, maxY),
newX = _constrain(currentX, minX, maxX),
duration = sv.get(SNAP_DURATION),
easing = sv.get(SNAP_EASING);
if (newX !== currentX) {
sv.set(SCROLL_X, newX, {duration:duration, easing:easing});
}
else if (newY !== currentY) {
sv.set(SCROLL_Y, newY, {duration:duration, easing:easing});
}
else {
sv._onTransEnd();
}
},
/**
* After listener for changes to the scrollX or scrollY attribute
*
* @method _afterScrollChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterScrollChange: function (e) {
if (e.src === ScrollView.UI_SRC) {
return false;
}
var sv = this,
duration = e.duration,
easing = e.easing,
val = e.newVal,
scrollToArgs = [];
// Set the scrolled value
sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal);
// Generate the array of args to pass to scrollTo()
if (e.attrName === SCROLL_X) {
scrollToArgs.push(val);
scrollToArgs.push(sv.get(SCROLL_Y));
}
else {
scrollToArgs.push(sv.get(SCROLL_X));
scrollToArgs.push(val);
}
scrollToArgs.push(duration);
scrollToArgs.push(easing);
sv.scrollTo.apply(sv, scrollToArgs);
},
/**
* After listener for changes to the flick attribute
*
* @method _afterFlickChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterFlickChange: function (e) {
this._bindFlick(e.newVal);
},
/**
* After listener for changes to the disabled attribute
*
* @method _afterDisabledChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterDisabledChange: function (e) {
// Cache for performance - we check during move
this._cDisabled = e.newVal;
},
/**
* After listener for the axis attribute
*
* @method _afterAxisChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterAxisChange: function (e) {
this._cAxis = e.newVal;
},
/**
* After listener for changes to the drag attribute
*
* @method _afterDragChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterDragChange: function (e) {
this._bindDrag(e.newVal);
},
/**
* After listener for the height or width attribute
*
* @method _afterDimChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterDimChange: function () {
this._uiDimensionsChange();
},
/**
* After listener for scrollEnd, for cleanup
*
* @method _afterScrollEnd
* @param e {Event.Facade} The event facade
* @protected
*/
_afterScrollEnd: function () {
var sv = this;
if (sv._flickAnim) {
sv._cancelFlick();
}
// Ideally this should be removed, but doing so causing some JS errors with fast swiping
// because _gesture is being deleted after the previous one has been overwritten
// delete sv._gesture; // TODO: Move to sv.prevGesture?
},
/**
* Setter for 'axis' attribute
*
* @method _axisSetter
* @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on
* @param name {String} The attribute name
* @return {Object} An object to specify scrollability on the x & y axes
*
* @protected
*/
_axisSetter: function (val) {
// Turn a string into an axis object
if (Y.Lang.isString(val)) {
return {
x: val.match(/x/i) ? true : false,
y: val.match(/y/i) ? true : false
};
}
},
/**
* The scrollX, scrollY setter implementation
*
* @method _setScroll
* @private
* @param {Number} val
* @param {String} dim
*
* @return {Number} The value
*/
_setScroll : function(val) {
// Just ensure the widget is not disabled
if (this._cDisabled) {
val = Y.Attribute.INVALID_VALUE;
}
return val;
},
/**
* Setter for the scrollX attribute
*
* @method _setScrollX
* @param val {Number} The new scrollX value
* @return {Number} The normalized value
* @protected
*/
_setScrollX: function(val) {
return this._setScroll(val, DIM_X);
},
/**
* Setter for the scrollY ATTR
*
* @method _setScrollY
* @param val {Number} The new scrollY value
* @return {Number} The normalized value
* @protected
*/
_setScrollY: function(val) {
return this._setScroll(val, DIM_Y);
}
// End prototype properties
}, {
// Static properties
/**
* The identity of the widget.
*
* @property NAME
* @type String
* @default 'scrollview'
* @readOnly
* @protected
* @static
*/
NAME: 'scrollview',
/**
* Static property used to define the default attribute configuration of
* the Widget.
*
* @property ATTRS
* @type {Object}
* @protected
* @static
*/
ATTRS: {
/**
* Specifies ability to scroll on x, y, or x and y axis/axes.
*
* @attribute axis
* @type String
*/
axis: {
setter: '_axisSetter',
writeOnce: 'initOnly'
},
/**
* The current scroll position in the x-axis
*
* @attribute scrollX
* @type Number
* @default 0
*/
scrollX: {
value: 0,
setter: '_setScrollX'
},
/**
* The current scroll position in the y-axis
*
* @attribute scrollY
* @type Number
* @default 0
*/
scrollY: {
value: 0,
setter: '_setScrollY'
},
/**
* Drag coefficent for inertial scrolling. The closer to 1 this
* value is, the less friction during scrolling.
*
* @attribute deceleration
* @default 0.93
*/
deceleration: {
value: 0.93
},
/**
* Drag coefficient for intertial scrolling at the upper
* and lower boundaries of the scrollview. Set to 0 to
* disable "rubber-banding".
*
* @attribute bounce
* @type Number
* @default 0.1
*/
bounce: {
value: 0.1
},
/**
* The minimum distance and/or velocity which define a flick. Can be set to false,
* to disable flick support (note: drag support is enabled/disabled separately)
*
* @attribute flick
* @type Object
* @default Object with properties minDistance = 10, minVelocity = 0.3.
*/
flick: {
value: {
minDistance: 10,
minVelocity: 0.3
}
},
/**
* Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately)
* @attribute drag
* @type boolean
* @default true
*/
drag: {
value: true
},
/**
* The default duration to use when animating the bounce snap back.
*
* @attribute snapDuration
* @type Number
* @default 400
*/
snapDuration: {
value: 400
},
/**
* The default easing to use when animating the bounce snap back.
*
* @attribute snapEasing
* @type String
* @default 'ease-out'
*/
snapEasing: {
value: 'ease-out'
},
/**
* The default easing used when animating the flick
*
* @attribute easing
* @type String
* @default 'cubic-bezier(0, 0.1, 0, 1.0)'
*/
easing: {
value: 'cubic-bezier(0, 0.1, 0, 1.0)'
},
/**
* The interval (ms) used when animating the flick for JS-timer animations
*
* @attribute frameDuration
* @type Number
* @default 15
*/
frameDuration: {
value: 15
},
/**
* The default bounce distance in pixels
*
* @attribute bounceRange
* @type Number
* @default 150
*/
bounceRange: {
value: 150
}
},
/**
* List of class names used in the scrollview's DOM
*
* @property CLASS_NAMES
* @type Object
* @static
*/
CLASS_NAMES: CLASS_NAMES,
/**
* Flag used to source property changes initiated from the DOM
*
* @property UI_SRC
* @type String
* @static
* @default 'ui'
*/
UI_SRC: UI,
/**
* Object map of style property names used to set transition properties.
* Defaults to the vendor prefix established by the Transition module.
* The configured property names are `_TRANSITION.DURATION` (e.g. "WebkitTransitionDuration") and
* `_TRANSITION.PROPERTY (e.g. "WebkitTransitionProperty").
*
* @property _TRANSITION
* @private
*/
_TRANSITION: {
DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'),
PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty')
},
/**
* The default bounce distance in pixels
*
* @property BOUNCE_RANGE
* @type Number
* @static
* @default false
* @deprecated (in 3.7.0)
*/
BOUNCE_RANGE: false,
/**
* The interval (ms) used when animating the flick
*
* @property FRAME_STEP
* @type Number
* @static
* @default false
* @deprecated (in 3.7.0)
*/
FRAME_STEP: false,
/**
* The default easing used when animating the flick
*
* @property EASING
* @type String
* @static
* @default false
* @deprecated (in 3.7.0)
*/
EASING: false,
/**
* The default easing to use when animating the bounce snap back.
*
* @property SNAP_EASING
* @type String
* @static
* @default false
* @deprecated (in 3.7.0)
*/
SNAP_EASING: false,
/**
* The default duration to use when animating the bounce snap back.
*
* @property SNAP_DURATION
* @type Number
* @static
* @default false
* @deprecated (in 3.7.0)
*/
SNAP_DURATION: false
// End static properties
});
}, '@VERSION@', {"requires": ["widget", "event-gestures", "event-mousewheel", "transition"], "skinnable": true});
|
ajax/libs/react-data-grid/0.14.26/react-data-grid-with-addons.js | Piicksarn/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["ReactDataGrid"] = factory(require("react"), require("react-dom"));
else
root["ReactDataGrid"] = 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);
module.exports.Editors = __webpack_require__(40);
module.exports.Formatters = __webpack_require__(44);
module.exports.Toolbar = __webpack_require__(46);
module.exports.Row = __webpack_require__(24);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(3);
var BaseGrid = __webpack_require__(4);
var Row = __webpack_require__(24);
var ExcelColumn = __webpack_require__(15);
var KeyboardHandlerMixin = __webpack_require__(27);
var CheckboxEditor = __webpack_require__(36);
var DOMMetrics = __webpack_require__(34);
var ColumnMetricsMixin = __webpack_require__(37);
var RowUtils = __webpack_require__(39);
var ColumnUtils = __webpack_require__(10);
if (!Object.assign) {
Object.assign = __webpack_require__(38);
}
var ReactDataGrid = React.createClass({
displayName: 'ReactDataGrid',
mixins: [ColumnMetricsMixin, DOMMetrics.MetricsComputatorMixin, KeyboardHandlerMixin],
propTypes: {
rowHeight: React.PropTypes.number.isRequired,
headerRowHeight: React.PropTypes.number,
minHeight: React.PropTypes.number.isRequired,
minWidth: React.PropTypes.number,
enableRowSelect: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.string]),
onRowUpdated: React.PropTypes.func,
rowGetter: React.PropTypes.func.isRequired,
rowsCount: React.PropTypes.number.isRequired,
toolbar: React.PropTypes.element,
enableCellSelect: React.PropTypes.bool,
columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired,
onFilter: React.PropTypes.func,
onCellCopyPaste: React.PropTypes.func,
onCellsDragged: React.PropTypes.func,
onAddFilter: React.PropTypes.func,
onGridSort: React.PropTypes.func,
onDragHandleDoubleClick: React.PropTypes.func,
onGridRowsUpdated: React.PropTypes.func,
onRowSelect: React.PropTypes.func,
rowKey: React.PropTypes.string,
rowScrollTimeout: React.PropTypes.number,
onClearFilters: React.PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
enableCellSelect: false,
tabIndex: -1,
rowHeight: 35,
enableRowSelect: false,
minHeight: 350,
rowKey: 'id',
rowScrollTimeout: 0
};
},
getInitialState: function getInitialState() {
var columnMetrics = this.createColumnMetrics();
var initialState = { columnMetrics: columnMetrics, selectedRows: [], copied: null, expandedRows: [], canFilter: false, columnFilters: {}, sortDirection: null, sortColumn: null, dragged: null, scrollOffset: 0 };
if (this.props.enableCellSelect) {
initialState.selected = { rowIdx: 0, idx: 0 };
} else {
initialState.selected = { rowIdx: -1, idx: -1 };
}
return initialState;
},
onSelect: function onSelect(selected) {
if (this.props.enableCellSelect) {
if (this.state.selected.rowIdx !== selected.rowIdx || this.state.selected.idx !== selected.idx || this.state.selected.active === false) {
var _idx = selected.idx;
var _rowIdx = selected.rowIdx;
if (_idx >= 0 && _rowIdx >= 0 && _idx < ColumnUtils.getSize(this.state.columnMetrics.columns) && _rowIdx < this.props.rowsCount) {
this.setState({ selected: selected });
}
}
}
},
onCellClick: function onCellClick(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx });
},
onCellDoubleClick: function onCellDoubleClick(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx });
this.setActive('Enter');
},
onViewportDoubleClick: function onViewportDoubleClick() {
this.setActive();
},
onPressArrowUp: function onPressArrowUp(e) {
this.moveSelectedCell(e, -1, 0);
},
onPressArrowDown: function onPressArrowDown(e) {
this.moveSelectedCell(e, 1, 0);
},
onPressArrowLeft: function onPressArrowLeft(e) {
this.moveSelectedCell(e, 0, -1);
},
onPressArrowRight: function onPressArrowRight(e) {
this.moveSelectedCell(e, 0, 1);
},
onPressTab: function onPressTab(e) {
this.moveSelectedCell(e, 0, e.shiftKey ? -1 : 1);
},
onPressEnter: function onPressEnter(e) {
this.setActive(e.key);
},
onPressDelete: function onPressDelete(e) {
this.setActive(e.key);
},
onPressEscape: function onPressEscape(e) {
this.setInactive(e.key);
},
onPressBackspace: function onPressBackspace(e) {
this.setActive(e.key);
},
onPressChar: function onPressChar(e) {
if (this.isKeyPrintable(e.keyCode)) {
this.setActive(e.keyCode);
}
},
onPressKeyWithCtrl: function onPressKeyWithCtrl(e) {
var keys = {
KeyCode_c: 99,
KeyCode_C: 67,
KeyCode_V: 86,
KeyCode_v: 118
};
var idx = this.state.selected.idx;
if (this.canEdit(idx)) {
if (e.keyCode === keys.KeyCode_c || e.keyCode === keys.KeyCode_C) {
var _value = this.getSelectedValue();
this.handleCopy({ value: _value });
} else if (e.keyCode === keys.KeyCode_v || e.keyCode === keys.KeyCode_V) {
this.handlePaste();
}
}
},
onCellCommit: function onCellCommit(commit) {
var selected = Object.assign({}, this.state.selected);
selected.active = false;
if (commit.key === 'Tab') {
selected.idx += 1;
}
var expandedRows = this.state.expandedRows;
// if(commit.changed && commit.changed.expandedHeight){
// expandedRows = this.expandRow(commit.rowIdx, commit.changed.expandedHeight);
// }
this.setState({ selected: selected, expandedRows: expandedRows });
if (this.props.onRowUpdated) {
this.props.onRowUpdated(commit);
}
var targetRow = commit.rowIdx;
if (this.props.onGridRowsUpdated) {
this.props.onGridRowsUpdated({
cellKey: commit.cellKey,
fromRow: targetRow,
toRow: targetRow,
updated: commit.updated,
action: 'cellUpdate' });
}
},
onDragStart: function onDragStart(e) {
var value = this.getSelectedValue();
this.handleDragStart({ idx: this.state.selected.idx, rowIdx: this.state.selected.rowIdx, value: value });
// need to set dummy data for FF
if (e && e.dataTransfer) {
if (e.dataTransfer.setData) {
e.dataTransfer.dropEffect = 'move';
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', 'dummy');
}
}
},
onToggleFilter: function onToggleFilter() {
this.setState({ canFilter: !this.state.canFilter });
if (this.state.canFilter === false && this.props.onClearFilters) {
this.props.onClearFilters();
}
},
onDragHandleDoubleClick: function onDragHandleDoubleClick(e) {
if (this.props.onDragHandleDoubleClick) {
this.props.onDragHandleDoubleClick(e);
}
if (this.props.onGridRowsUpdated) {
var cellKey = this.getColumn(e.idx).key;
var updated = _defineProperty({}, cellKey, e.rowData[cellKey]);
this.props.onGridRowsUpdated({
cellKey: cellKey,
fromRow: e.rowIdx,
toRow: this.props.rowsCount - 1,
updated: updated,
action: 'columnFill' });
}
},
handleDragStart: function handleDragStart(dragged) {
if (!this.dragEnabled()) {
return;
}
var idx = dragged.idx;
var rowIdx = dragged.rowIdx;
if (idx >= 0 && rowIdx >= 0 && idx < this.getSize() && rowIdx < this.props.rowsCount) {
this.setState({ dragged: dragged });
}
},
handleDragEnd: function handleDragEnd() {
if (!this.dragEnabled()) {
return;
}
var fromRow = void 0;
var toRow = void 0;
var selected = this.state.selected;
var dragged = this.state.dragged;
var cellKey = this.getColumn(this.state.selected.idx).key;
fromRow = selected.rowIdx < dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx;
toRow = selected.rowIdx > dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx;
if (this.props.onCellsDragged) {
this.props.onCellsDragged({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, value: dragged.value });
}
if (this.props.onGridRowsUpdated) {
var updated = _defineProperty({}, cellKey, dragged.value);
this.props.onGridRowsUpdated({
cellKey: cellKey,
fromRow: fromRow,
toRow: toRow,
updated: updated,
action: 'cellDrag' });
}
this.setState({ dragged: { complete: true } });
},
handleDragEnter: function handleDragEnter(row) {
if (!this.dragEnabled()) {
return;
}
var dragged = this.state.dragged;
dragged.overRowIdx = row;
this.setState({ dragged: dragged });
},
handleTerminateDrag: function handleTerminateDrag() {
if (!this.dragEnabled()) {
return;
}
this.setState({ dragged: null });
},
handlePaste: function handlePaste() {
if (!this.copyPasteEnabled()) {
return;
}
var selected = this.state.selected;
var cellKey = this.getColumn(this.state.selected.idx).key;
var textToCopy = this.state.textToCopy;
var toRow = selected.rowIdx;
if (this.props.onCellCopyPaste) {
this.props.onCellCopyPaste({ cellKey: cellKey, rowIdx: toRow, value: textToCopy, fromRow: this.state.copied.rowIdx, toRow: toRow });
}
if (this.props.onGridRowsUpdated) {
var updated = _defineProperty({}, cellKey, textToCopy);
this.props.onGridRowsUpdated({
cellKey: cellKey,
fromRow: toRow,
toRow: toRow,
updated: updated,
action: 'copyPaste' });
}
this.setState({ copied: null });
},
handleCopy: function handleCopy(args) {
if (!this.copyPasteEnabled()) {
return;
}
var textToCopy = args.value;
var selected = this.state.selected;
var copied = { idx: selected.idx, rowIdx: selected.rowIdx };
this.setState({ textToCopy: textToCopy, copied: copied });
},
handleSort: function handleSort(columnKey, direction) {
this.setState({ sortDirection: direction, sortColumn: columnKey }, function () {
this.props.onGridSort(columnKey, direction);
});
},
getSelectedRow: function getSelectedRow(rows, key) {
var _this = this;
var selectedRow = rows.filter(function (r) {
if (r[_this.props.rowKey] === key) {
return true;
}
return false;
});
if (selectedRow.length > 0) {
return selectedRow[0];
}
},
// columnKey not used here as this function will select the whole row,
// but needed to match the function signature in the CheckboxEditor
handleRowSelect: function handleRowSelect(rowIdx, columnKey, rowData, e) {
e.stopPropagation();
var selectedRows = this.props.enableRowSelect === 'single' ? [] : this.state.selectedRows.slice(0);
var selectedRow = this.getSelectedRow(selectedRows, rowData[this.props.rowKey]);
if (selectedRow) {
selectedRow.isSelected = !selectedRow.isSelected;
} else {
rowData.isSelected = true;
selectedRows.push(rowData);
}
this.setState({ selectedRows: selectedRows, selected: { rowIdx: rowIdx, idx: 0 } });
if (this.props.onRowSelect) {
this.props.onRowSelect(selectedRows.filter(function (r) {
return r.isSelected === true;
}));
}
},
handleCheckboxChange: function handleCheckboxChange(e) {
var allRowsSelected = void 0;
if (e.currentTarget instanceof HTMLInputElement && e.currentTarget.checked === true) {
allRowsSelected = true;
} else {
allRowsSelected = false;
}
var selectedRows = [];
for (var i = 0; i < this.props.rowsCount; i++) {
var row = Object.assign({}, this.props.rowGetter(i), { isSelected: allRowsSelected });
selectedRows.push(row);
}
this.setState({ selectedRows: selectedRows });
if (typeof this.props.onRowSelect === 'function') {
this.props.onRowSelect(selectedRows.filter(function (r) {
return r.isSelected === true;
}));
}
},
getScrollOffSet: function getScrollOffSet() {
var scrollOffset = 0;
var canvas = ReactDOM.findDOMNode(this).querySelector('.react-grid-Canvas');
if (canvas) {
scrollOffset = canvas.offsetWidth - canvas.clientWidth;
}
this.setState({ scrollOffset: scrollOffset });
},
getRowOffsetHeight: function getRowOffsetHeight() {
var offsetHeight = 0;
this.getHeaderRows().forEach(function (row) {
return offsetHeight += parseFloat(row.height, 10);
});
return offsetHeight;
},
getHeaderRows: function getHeaderRows() {
var rows = [{ ref: 'row', height: this.props.headerRowHeight || this.props.rowHeight }];
if (this.state.canFilter === true) {
rows.push({
ref: 'filterRow',
filterable: true,
onFilterChange: this.props.onAddFilter,
height: 45
});
}
return rows;
},
getInitialSelectedRows: function getInitialSelectedRows() {
var selectedRows = [];
for (var i = 0; i < this.props.rowsCount; i++) {
selectedRows.push(false);
}
return selectedRows;
},
getSelectedValue: function getSelectedValue() {
var rowIdx = this.state.selected.rowIdx;
var idx = this.state.selected.idx;
var cellKey = this.getColumn(idx).key;
var row = this.props.rowGetter(rowIdx);
return RowUtils.get(row, cellKey);
},
moveSelectedCell: function moveSelectedCell(e, rowDelta, cellDelta) {
// we need to prevent default as we control grid scroll
// otherwise it moves every time you left/right which is janky
e.preventDefault();
var rowIdx = this.state.selected.rowIdx + rowDelta;
var idx = this.state.selected.idx + cellDelta;
this.onSelect({ idx: idx, rowIdx: rowIdx });
},
setActive: function setActive(keyPressed) {
var rowIdx = this.state.selected.rowIdx;
var idx = this.state.selected.idx;
if (this.canEdit(idx) && !this.isActive()) {
var _selected = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: true, initialKeyCode: keyPressed });
this.setState({ selected: _selected });
}
},
setInactive: function setInactive() {
var rowIdx = this.state.selected.rowIdx;
var idx = this.state.selected.idx;
if (this.canEdit(idx) && this.isActive()) {
var _selected2 = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: false });
this.setState({ selected: _selected2 });
}
},
canEdit: function canEdit(idx) {
var col = this.getColumn(idx);
return this.props.enableCellSelect === true && (col.editor != null || col.editable);
},
isActive: function isActive() {
return this.state.selected.active === true;
},
setupGridColumns: function setupGridColumns() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
var cols = props.columns.slice(0);
var unshiftedCols = {};
if (props.enableRowSelect) {
var headerRenderer = props.enableRowSelect === 'single' ? null : React.createElement(
'div',
{ className: 'react-grid-checkbox-container' },
React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: 'select-all-checkbox', onChange: this.handleCheckboxChange }),
React.createElement('label', { htmlFor: 'select-all-checkbox', className: 'react-grid-checkbox-label' })
);
var selectColumn = {
key: 'select-row',
name: '',
formatter: React.createElement(CheckboxEditor, null),
onCellChange: this.handleRowSelect,
filterable: false,
headerRenderer: headerRenderer,
width: 60,
locked: true,
getRowMetaData: function getRowMetaData(rowData) {
return rowData;
}
};
unshiftedCols = cols.unshift(selectColumn);
cols = unshiftedCols > 0 ? cols : unshiftedCols;
}
return cols;
},
copyPasteEnabled: function copyPasteEnabled() {
return this.props.onCellCopyPaste !== null;
},
dragEnabled: function dragEnabled() {
return this.props.onCellsDragged !== null;
},
renderToolbar: function renderToolbar() {
var Toolbar = this.props.toolbar;
if (React.isValidElement(Toolbar)) {
return React.cloneElement(Toolbar, { onToggleFilter: this.onToggleFilter, numberOfRows: this.props.rowsCount });
}
},
render: function render() {
var cellMetaData = {
selected: this.state.selected,
dragged: this.state.dragged,
onCellClick: this.onCellClick,
onCellDoubleClick: this.onCellDoubleClick,
onCommit: this.onCellCommit,
onCommitCancel: this.setInactive,
copied: this.state.copied,
handleDragEnterRow: this.handleDragEnter,
handleTerminateDrag: this.handleTerminateDrag,
onDragHandleDoubleClick: this.onDragHandleDoubleClick
};
var toolbar = this.renderToolbar();
var containerWidth = this.props.minWidth || this.DOMMetrics.gridWidth();
var gridWidth = containerWidth - this.state.scrollOffset;
// depending on the current lifecycle stage, gridWidth() may not initialize correctly
// this also handles cases where it always returns undefined -- such as when inside a div with display:none
// eg Bootstrap tabs and collapses
if (typeof containerWidth === 'undefined' || isNaN(containerWidth) || containerWidth === 0) {
containerWidth = '100%';
}
if (typeof gridWidth === 'undefined' || isNaN(gridWidth) || gridWidth === 0) {
gridWidth = '100%';
}
return React.createElement(
'div',
{ className: 'react-grid-Container', style: { width: containerWidth } },
toolbar,
React.createElement(
'div',
{ className: 'react-grid-Main' },
React.createElement(BaseGrid, _extends({
ref: 'base'
}, this.props, {
rowKey: this.props.rowKey,
headerRows: this.getHeaderRows(),
columnMetrics: this.state.columnMetrics,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
rowHeight: this.props.rowHeight,
cellMetaData: cellMetaData,
selectedRows: this.state.selectedRows.filter(function (r) {
return r.isSelected === true;
}),
expandedRows: this.state.expandedRows,
rowOffsetHeight: this.getRowOffsetHeight(),
sortColumn: this.state.sortColumn,
sortDirection: this.state.sortDirection,
onSort: this.handleSort,
minHeight: this.props.minHeight,
totalWidth: gridWidth,
onViewportKeydown: this.onKeyDown,
onViewportDragStart: this.onDragStart,
onViewportDragEnd: this.handleDragEnd,
onViewportDoubleClick: this.onViewportDoubleClick,
onColumnResize: this.onColumnResize,
rowScrollTimeout: this.props.rowScrollTimeout }))
)
);
}
});
module.exports = ReactDataGrid;
/***/ },
/* 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__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(2);
var PropTypes = React.PropTypes;
var Header = __webpack_require__(5);
var Viewport = __webpack_require__(21);
var GridScrollMixin = __webpack_require__(35);
var DOMMetrics = __webpack_require__(34);
var cellMetaDataShape = __webpack_require__(31);
var Grid = React.createClass({
displayName: 'Grid',
propTypes: {
rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired,
columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
columnMetrics: PropTypes.object,
minHeight: PropTypes.number,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
headerRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
rowHeight: PropTypes.number,
rowRenderer: PropTypes.func,
emptyRowsView: PropTypes.func,
expandedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
selectedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
rowsCount: PropTypes.number,
onRows: PropTypes.func,
sortColumn: React.PropTypes.string,
sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']),
rowOffsetHeight: PropTypes.number.isRequired,
onViewportKeydown: PropTypes.func.isRequired,
onViewportDragStart: PropTypes.func.isRequired,
onViewportDragEnd: PropTypes.func.isRequired,
onViewportDoubleClick: PropTypes.func.isRequired,
onColumnResize: PropTypes.func,
onSort: PropTypes.func,
cellMetaData: PropTypes.shape(cellMetaDataShape),
rowKey: PropTypes.string.isRequired,
rowScrollTimeout: PropTypes.number
},
mixins: [GridScrollMixin, DOMMetrics.MetricsComputatorMixin],
getDefaultProps: function getDefaultProps() {
return {
rowHeight: 35,
minHeight: 350
};
},
getStyle: function getStyle() {
return {
overflow: 'hidden',
outline: 0,
position: 'relative',
minHeight: this.props.minHeight
};
},
render: function render() {
var headerRows = this.props.headerRows || [{ ref: 'row' }];
var EmptyRowsView = this.props.emptyRowsView;
return React.createElement(
'div',
_extends({}, this.props, { style: this.getStyle(), className: 'react-grid-Grid' }),
React.createElement(Header, {
ref: 'header',
columnMetrics: this.props.columnMetrics,
onColumnResize: this.props.onColumnResize,
height: this.props.rowHeight,
totalWidth: this.props.totalWidth,
headerRows: headerRows,
sortColumn: this.props.sortColumn,
sortDirection: this.props.sortDirection,
onSort: this.props.onSort,
onScroll: this.onHeaderScroll
}),
this.props.rowsCount >= 1 || this.props.rowsCount === 0 && !this.props.emptyRowsView ? React.createElement(
'div',
{ ref: 'viewPortContainer', onKeyDown: this.props.onViewportKeydown, onDoubleClick: this.props.onViewportDoubleClick, onDragStart: this.props.onViewportDragStart, onDragEnd: this.props.onViewportDragEnd },
React.createElement(Viewport, {
ref: 'viewport',
rowKey: this.props.rowKey,
width: this.props.columnMetrics.width,
rowHeight: this.props.rowHeight,
rowRenderer: this.props.rowRenderer,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
selectedRows: this.props.selectedRows,
expandedRows: this.props.expandedRows,
columnMetrics: this.props.columnMetrics,
totalWidth: this.props.totalWidth,
onScroll: this.onScroll,
onRows: this.props.onRows,
cellMetaData: this.props.cellMetaData,
rowOffsetHeight: this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length,
minHeight: this.props.minHeight,
rowScrollTimeout: this.props.rowScrollTimeout
})
) : React.createElement(
'div',
{ ref: 'emptyView', className: 'react-grid-Empty' },
React.createElement(EmptyRowsView, null)
)
);
}
});
module.exports = Grid;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(3);
var joinClasses = __webpack_require__(6);
var shallowCloneObject = __webpack_require__(7);
var ColumnMetrics = __webpack_require__(8);
var ColumnUtils = __webpack_require__(10);
var HeaderRow = __webpack_require__(12);
var PropTypes = React.PropTypes;
var Header = React.createClass({
displayName: 'Header',
propTypes: {
columnMetrics: PropTypes.shape({ width: PropTypes.number.isRequired, columns: PropTypes.any }).isRequired,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.number.isRequired,
headerRows: PropTypes.array.isRequired,
sortColumn: PropTypes.string,
sortDirection: PropTypes.oneOf(['ASC', 'DESC', 'NONE']),
onSort: PropTypes.func,
onColumnResize: PropTypes.func,
onScroll: PropTypes.func
},
getInitialState: function getInitialState() {
return { resizing: null };
},
componentWillReceiveProps: function componentWillReceiveProps() {
this.setState({ resizing: null });
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
var update = !ColumnMetrics.sameColumns(this.props.columnMetrics.columns, nextProps.columnMetrics.columns, ColumnMetrics.sameColumn) || this.props.totalWidth !== nextProps.totalWidth || this.props.headerRows.length !== nextProps.headerRows.length || this.state.resizing !== nextState.resizing || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection;
return update;
},
onColumnResize: function onColumnResize(column, width) {
var state = this.state.resizing || this.props;
var pos = this.getColumnPosition(column);
if (pos != null) {
var _resizing = {
columnMetrics: shallowCloneObject(state.columnMetrics)
};
_resizing.columnMetrics = ColumnMetrics.resizeColumn(_resizing.columnMetrics, pos, width);
// we don't want to influence scrollLeft while resizing
if (_resizing.columnMetrics.totalWidth < state.columnMetrics.totalWidth) {
_resizing.columnMetrics.totalWidth = state.columnMetrics.totalWidth;
}
_resizing.column = ColumnUtils.getColumn(_resizing.columnMetrics.columns, pos);
this.setState({ resizing: _resizing });
}
},
onColumnResizeEnd: function onColumnResizeEnd(column, width) {
var pos = this.getColumnPosition(column);
if (pos !== null && this.props.onColumnResize) {
this.props.onColumnResize(pos, width || column.width);
}
},
getHeaderRows: function getHeaderRows() {
var _this = this;
var columnMetrics = this.getColumnMetrics();
var resizeColumn = void 0;
if (this.state.resizing) {
resizeColumn = this.state.resizing.column;
}
var headerRows = [];
this.props.headerRows.forEach(function (row, index) {
var headerRowStyle = {
position: 'absolute',
top: _this.getCombinedHeaderHeights(index),
left: 0,
width: _this.props.totalWidth,
overflow: 'hidden'
};
headerRows.push(React.createElement(HeaderRow, {
key: row.ref,
ref: row.ref,
style: headerRowStyle,
onColumnResize: _this.onColumnResize,
onColumnResizeEnd: _this.onColumnResizeEnd,
width: columnMetrics.width,
height: row.height || _this.props.height,
columns: columnMetrics.columns,
resizing: resizeColumn,
filterable: row.filterable,
onFilterChange: row.onFilterChange,
sortColumn: _this.props.sortColumn,
sortDirection: _this.props.sortDirection,
onSort: _this.props.onSort,
onScroll: _this.props.onScroll
}));
});
return headerRows;
},
getColumnMetrics: function getColumnMetrics() {
var columnMetrics = void 0;
if (this.state.resizing) {
columnMetrics = this.state.resizing.columnMetrics;
} else {
columnMetrics = this.props.columnMetrics;
}
return columnMetrics;
},
getColumnPosition: function getColumnPosition(column) {
var columnMetrics = this.getColumnMetrics();
var pos = -1;
columnMetrics.columns.forEach(function (c, idx) {
if (c.key === column.key) {
pos = idx;
}
});
return pos === -1 ? null : pos;
},
getCombinedHeaderHeights: function getCombinedHeaderHeights(until) {
var stopAt = this.props.headerRows.length;
if (typeof until !== 'undefined') {
stopAt = until;
}
var height = 0;
for (var index = 0; index < stopAt; index++) {
height += this.props.headerRows[index].height || this.props.height;
}
return height;
},
getStyle: function getStyle() {
return {
position: 'relative',
height: this.getCombinedHeaderHeights(),
overflow: 'hidden'
};
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var node = ReactDOM.findDOMNode(this.refs.row);
node.scrollLeft = scrollLeft;
this.refs.row.setScrollLeft(scrollLeft);
if (this.refs.filterRow) {
var nodeFilters = ReactDOM.findDOMNode(this.refs.filterRow);
nodeFilters.scrollLeft = scrollLeft;
this.refs.filterRow.setScrollLeft(scrollLeft);
}
},
render: function render() {
var className = joinClasses({
'react-grid-Header': true,
'react-grid-Header--resizing': !!this.state.resizing
});
var headerRows = this.getHeaderRows();
return React.createElement(
'div',
_extends({}, this.props, { style: this.getStyle(), className: className }),
headerRows
);
}
});
module.exports = Header;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
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 (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
/***/ },
/* 7 */
/***/ function(module, exports) {
"use strict";
function shallowCloneObject(obj) {
var result = {};
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
result[k] = obj[k];
}
}
return result;
}
module.exports = shallowCloneObject;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var shallowCloneObject = __webpack_require__(7);
var sameColumn = __webpack_require__(9);
var ColumnUtils = __webpack_require__(10);
var getScrollbarSize = __webpack_require__(11);
function setColumnWidths(columns, totalWidth) {
return columns.map(function (column) {
var colInfo = Object.assign({}, column);
if (column.width) {
if (/^([0-9]+)%$/.exec(column.width.toString())) {
colInfo.width = Math.floor(column.width / 100 * totalWidth);
}
}
return colInfo;
});
}
function setDefferedColumnWidths(columns, unallocatedWidth, minColumnWidth) {
var defferedColumns = columns.filter(function (c) {
return !c.width;
});
return columns.map(function (column) {
if (!column.width) {
if (unallocatedWidth <= 0) {
column.width = minColumnWidth;
} else {
column.width = Math.floor(unallocatedWidth / ColumnUtils.getSize(defferedColumns));
}
}
return column;
});
}
function setColumnOffsets(columns) {
var left = 0;
return columns.map(function (column) {
column.left = left;
left += column.width;
return column;
});
}
/**
* Update column metrics calculation.
*
* @param {ColumnMetricsType} metrics
*/
function recalculate(metrics) {
// compute width for columns which specify width
var columns = setColumnWidths(metrics.columns, metrics.totalWidth);
var unallocatedWidth = columns.filter(function (c) {
return c.width;
}).reduce(function (w, column) {
return w - column.width;
}, metrics.totalWidth);
unallocatedWidth -= getScrollbarSize();
var width = columns.filter(function (c) {
return c.width;
}).reduce(function (w, column) {
return w + column.width;
}, 0);
// compute width for columns which doesn't specify width
columns = setDefferedColumnWidths(columns, unallocatedWidth, metrics.minColumnWidth);
// compute left offset
columns = setColumnOffsets(columns);
return {
columns: columns,
width: width,
totalWidth: metrics.totalWidth,
minColumnWidth: metrics.minColumnWidth
};
}
/**
* Update column metrics calculation by resizing a column.
*
* @param {ColumnMetricsType} metrics
* @param {Column} column
* @param {number} width
*/
function resizeColumn(metrics, index, width) {
var column = ColumnUtils.getColumn(metrics.columns, index);
var metricsClone = shallowCloneObject(metrics);
metricsClone.columns = metrics.columns.slice(0);
var updatedColumn = shallowCloneObject(column);
updatedColumn.width = Math.max(width, metricsClone.minColumnWidth);
metricsClone = ColumnUtils.spliceColumn(metricsClone, index, updatedColumn);
return recalculate(metricsClone);
}
function areColumnsImmutable(prevColumns, nextColumns) {
return typeof Immutable !== 'undefined' && prevColumns instanceof Immutable.List && nextColumns instanceof Immutable.List;
}
function compareEachColumn(prevColumns, nextColumns, isSameColumn) {
var i = void 0;
var len = void 0;
var column = void 0;
var prevColumnsByKey = {};
var nextColumnsByKey = {};
if (ColumnUtils.getSize(prevColumns) !== ColumnUtils.getSize(nextColumns)) {
return false;
}
for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) {
column = prevColumns[i];
prevColumnsByKey[column.key] = column;
}
for (i = 0, len = ColumnUtils.getSize(nextColumns); i < len; i++) {
column = nextColumns[i];
nextColumnsByKey[column.key] = column;
var prevColumn = prevColumnsByKey[column.key];
if (prevColumn === undefined || !isSameColumn(prevColumn, column)) {
return false;
}
}
for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) {
column = prevColumns[i];
var nextColumn = nextColumnsByKey[column.key];
if (nextColumn === undefined) {
return false;
}
}
return true;
}
function sameColumns(prevColumns, nextColumns, isSameColumn) {
if (areColumnsImmutable(prevColumns, nextColumns)) {
return prevColumns === nextColumns;
}
return compareEachColumn(prevColumns, nextColumns, isSameColumn);
}
module.exports = { recalculate: recalculate, resizeColumn: resizeColumn, sameColumn: sameColumn, sameColumns: sameColumns };
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var isValidElement = __webpack_require__(2).isValidElement;
module.exports = function sameColumn(a, b) {
var k = void 0;
for (k in a) {
if (a.hasOwnProperty(k)) {
if (typeof a[k] === 'function' && typeof b[k] === 'function' || isValidElement(a[k]) && isValidElement(b[k])) {
continue;
}
if (!b.hasOwnProperty(k) || a[k] !== b[k]) {
return false;
}
}
}
for (k in b) {
if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) {
return false;
}
}
return true;
};
/***/ },
/* 10 */
/***/ function(module, exports) {
'use strict';
module.exports = {
getColumn: function getColumn(columns, idx) {
if (Array.isArray(columns)) {
return columns[idx];
} else if (typeof Immutable !== 'undefined') {
return columns.get(idx);
}
},
spliceColumn: function spliceColumn(metrics, idx, column) {
if (Array.isArray(metrics.columns)) {
metrics.columns.splice(idx, 1, column);
} else if (typeof Immutable !== 'undefined') {
metrics.columns = metrics.columns.splice(idx, 1, column);
}
return metrics;
},
getSize: function getSize(columns) {
if (Array.isArray(columns)) {
return columns.length;
} else if (typeof Immutable !== 'undefined') {
return columns.size;
}
}
};
/***/ },
/* 11 */
/***/ function(module, exports) {
'use strict';
var size = void 0;
function getScrollbarSize() {
if (size === undefined) {
var outer = document.createElement('div');
outer.style.width = '50px';
outer.style.height = '50px';
outer.style.position = 'absolute';
outer.style.top = '-200px';
outer.style.left = '-200px';
var inner = document.createElement('div');
inner.style.height = '100px';
inner.style.width = '100%';
outer.appendChild(inner);
document.body.appendChild(outer);
var outerWidth = outer.clientWidth;
outer.style.overflowY = 'scroll';
var innerWidth = inner.clientWidth;
document.body.removeChild(outer);
size = outerWidth - innerWidth;
}
return size;
}
module.exports = getScrollbarSize;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(2);
var shallowEqual = __webpack_require__(13);
var HeaderCell = __webpack_require__(14);
var getScrollbarSize = __webpack_require__(11);
var ExcelColumn = __webpack_require__(15);
var ColumnUtilsMixin = __webpack_require__(10);
var SortableHeaderCell = __webpack_require__(18);
var FilterableHeaderCell = __webpack_require__(19);
var HeaderCellType = __webpack_require__(20);
var PropTypes = React.PropTypes;
var HeaderRowStyle = {
overflow: React.PropTypes.string,
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: React.PropTypes.number,
position: React.PropTypes.string
};
var DEFINE_SORT = ['ASC', 'DESC', 'NONE'];
var HeaderRow = React.createClass({
displayName: 'HeaderRow',
propTypes: {
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.number.isRequired,
columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
onColumnResize: PropTypes.func,
onSort: PropTypes.func.isRequired,
onColumnResizeEnd: PropTypes.func,
style: PropTypes.shape(HeaderRowStyle),
sortColumn: PropTypes.string,
sortDirection: React.PropTypes.oneOf(DEFINE_SORT),
cellRenderer: PropTypes.func,
headerCellRenderer: PropTypes.func,
filterable: PropTypes.bool,
onFilterChange: PropTypes.func,
resizing: PropTypes.func,
onScroll: PropTypes.func
},
mixins: [ColumnUtilsMixin],
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return nextProps.width !== this.props.width || nextProps.height !== this.props.height || nextProps.columns !== this.props.columns || !shallowEqual(nextProps.style, this.props.style) || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection;
},
getHeaderCellType: function getHeaderCellType(column) {
if (column.filterable) {
if (this.props.filterable) return HeaderCellType.FILTERABLE;
}
if (column.sortable) return HeaderCellType.SORTABLE;
return HeaderCellType.NONE;
},
getFilterableHeaderCell: function getFilterableHeaderCell() {
return React.createElement(FilterableHeaderCell, { onChange: this.props.onFilterChange });
},
getSortableHeaderCell: function getSortableHeaderCell(column) {
var sortDirection = this.props.sortColumn === column.key ? this.props.sortDirection : DEFINE_SORT.NONE;
return React.createElement(SortableHeaderCell, { columnKey: column.key, onSort: this.props.onSort, sortDirection: sortDirection });
},
getHeaderRenderer: function getHeaderRenderer(column) {
var renderer = void 0;
if (column.headerRenderer) {
renderer = column.headerRenderer;
} else {
var headerCellType = this.getHeaderCellType(column);
switch (headerCellType) {
case HeaderCellType.SORTABLE:
renderer = this.getSortableHeaderCell(column);
break;
case HeaderCellType.FILTERABLE:
renderer = this.getFilterableHeaderCell();
break;
default:
break;
}
}
return renderer;
},
getStyle: function getStyle() {
return {
overflow: 'hidden',
width: '100%',
height: this.props.height,
position: 'absolute'
};
},
getCells: function getCells() {
var cells = [];
var lockedCells = [];
for (var i = 0, len = this.getSize(this.props.columns); i < len; i++) {
var column = this.getColumn(this.props.columns, i);
var cell = React.createElement(HeaderCell, {
ref: i,
key: i,
height: this.props.height,
column: column,
renderer: this.getHeaderRenderer(column),
resizing: this.props.resizing === column,
onResize: this.props.onColumnResize,
onResizeEnd: this.props.onColumnResizeEnd
});
if (column.locked) {
lockedCells.push(cell);
} else {
cells.push(cell);
}
}
return cells.concat(lockedCells);
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var _this = this;
this.props.columns.forEach(function (column, i) {
if (column.locked) {
_this.refs[i].setScrollLeft(scrollLeft);
}
});
},
render: function render() {
var cellsStyle = {
width: this.props.width ? this.props.width + getScrollbarSize() : '100%',
height: this.props.height,
whiteSpace: 'nowrap',
overflowX: 'hidden',
overflowY: 'hidden'
};
var cells = this.getCells();
return React.createElement(
'div',
_extends({}, this.props, { className: 'react-grid-HeaderRow', onScroll: this.props.onScroll }),
React.createElement(
'div',
{ style: cellsStyle },
cells
)
);
}
});
module.exports = HeaderRow;
/***/ },
/* 13 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule shallowEqual
* @typechecks
*
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var bHasOwnProperty = hasOwnProperty.bind(objB);
for (var i = 0; i < keysA.length; i++) {
if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(3);
var joinClasses = __webpack_require__(6);
var ExcelColumn = __webpack_require__(15);
var ResizeHandle = __webpack_require__(16);
var PropTypes = React.PropTypes;
function simpleCellRenderer(objArgs) {
return React.createElement(
'div',
{ className: 'widget-HeaderCell__value' },
objArgs.column.name
);
}
var HeaderCell = React.createClass({
displayName: 'HeaderCell',
propTypes: {
renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]).isRequired,
column: PropTypes.shape(ExcelColumn).isRequired,
onResize: PropTypes.func.isRequired,
height: PropTypes.number.isRequired,
onResizeEnd: PropTypes.func.isRequired,
className: PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
renderer: simpleCellRenderer
};
},
getInitialState: function getInitialState() {
return { resizing: false };
},
onDragStart: function onDragStart(e) {
this.setState({ resizing: true });
// need to set dummy data for FF
if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy');
},
onDrag: function onDrag(e) {
var resize = this.props.onResize || null; // for flows sake, doesnt recognise a null check direct
if (resize) {
var _width = this.getWidthFromMouseEvent(e);
if (_width > 0) {
resize(this.props.column, _width);
}
}
},
onDragEnd: function onDragEnd(e) {
var width = this.getWidthFromMouseEvent(e);
this.props.onResizeEnd(this.props.column, width);
this.setState({ resizing: false });
},
getWidthFromMouseEvent: function getWidthFromMouseEvent(e) {
var right = e.pageX;
var left = ReactDOM.findDOMNode(this).getBoundingClientRect().left;
return right - left;
},
getCell: function getCell() {
if (React.isValidElement(this.props.renderer)) {
return React.cloneElement(this.props.renderer, { column: this.props.column });
}
return this.props.renderer({ column: this.props.column });
},
getStyle: function getStyle() {
return {
width: this.props.column.width,
left: this.props.column.left,
display: 'inline-block',
position: 'absolute',
overflow: 'hidden',
height: this.props.height,
margin: 0,
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
};
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var node = ReactDOM.findDOMNode(this);
node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
},
render: function render() {
var resizeHandle = void 0;
if (this.props.column.resizable) {
resizeHandle = React.createElement(ResizeHandle, {
onDrag: this.onDrag,
onDragStart: this.onDragStart,
onDragEnd: this.onDragEnd
});
}
var className = joinClasses({
'react-grid-HeaderCell': true,
'react-grid-HeaderCell--resizing': this.state.resizing,
'react-grid-HeaderCell--locked': this.props.column.locked
});
className = joinClasses(className, this.props.className, this.props.column.cellClass);
var cell = this.getCell();
return React.createElement(
'div',
{ className: className, style: this.getStyle() },
cell,
resizeHandle
);
}
});
module.exports = HeaderCell;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ExcelColumnShape = {
name: React.PropTypes.node.isRequired,
key: React.PropTypes.string.isRequired,
width: React.PropTypes.number.isRequired,
filterable: React.PropTypes.bool
};
module.exports = ExcelColumnShape;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(2);
var Draggable = __webpack_require__(17);
var ResizeHandle = React.createClass({
displayName: 'ResizeHandle',
style: {
position: 'absolute',
top: 0,
right: 0,
width: 6,
height: '100%'
},
render: function render() {
return React.createElement(Draggable, _extends({}, this.props, {
className: 'react-grid-HeaderCell__resizeHandle',
style: this.style
}));
}
});
module.exports = ResizeHandle;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(2);
var PropTypes = React.PropTypes;
var Draggable = React.createClass({
displayName: 'Draggable',
propTypes: {
onDragStart: PropTypes.func,
onDragEnd: PropTypes.func,
onDrag: PropTypes.func,
component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor])
},
getDefaultProps: function getDefaultProps() {
return {
onDragStart: function onDragStart() {
return true;
},
onDragEnd: function onDragEnd() {},
onDrag: function onDrag() {}
};
},
getInitialState: function getInitialState() {
return {
drag: null
};
},
componentWillUnmount: function componentWillUnmount() {
this.cleanUp();
},
onMouseDown: function onMouseDown(e) {
var drag = this.props.onDragStart(e);
if (drag === null && e.button !== 0) {
return;
}
window.addEventListener('mouseup', this.onMouseUp);
window.addEventListener('mousemove', this.onMouseMove);
this.setState({ drag: drag });
},
onMouseMove: function onMouseMove(e) {
if (this.state.drag === null) {
return;
}
if (e.preventDefault) {
e.preventDefault();
}
this.props.onDrag(e);
},
onMouseUp: function onMouseUp(e) {
this.cleanUp();
this.props.onDragEnd(e, this.state.drag);
this.setState({ drag: null });
},
cleanUp: function cleanUp() {
window.removeEventListener('mouseup', this.onMouseUp);
window.removeEventListener('mousemove', this.onMouseMove);
},
render: function render() {
return React.createElement('div', _extends({}, this.props, {
onMouseDown: this.onMouseDown,
className: 'react-grid-HeaderCell__draggable' }));
}
});
module.exports = Draggable;
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var joinClasses = __webpack_require__(6);
var DEFINE_SORT = {
ASC: 'ASC',
DESC: 'DESC',
NONE: 'NONE'
};
var SortableHeaderCell = React.createClass({
displayName: 'SortableHeaderCell',
propTypes: {
columnKey: React.PropTypes.string.isRequired,
column: React.PropTypes.shape({ name: React.PropTypes.node }),
onSort: React.PropTypes.func.isRequired,
sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE'])
},
onClick: function onClick() {
var direction = void 0;
switch (this.props.sortDirection) {
default:
case null:
case undefined:
case DEFINE_SORT.NONE:
direction = DEFINE_SORT.ASC;
break;
case DEFINE_SORT.ASC:
direction = DEFINE_SORT.DESC;
break;
case DEFINE_SORT.DESC:
direction = DEFINE_SORT.NONE;
break;
}
this.props.onSort(this.props.columnKey, direction);
},
getSortByText: function getSortByText() {
var unicodeKeys = {
ASC: '9650',
DESC: '9660',
NONE: ''
};
return String.fromCharCode(unicodeKeys[this.props.sortDirection]);
},
render: function render() {
var className = joinClasses({
'react-grid-HeaderCell-sortable': true,
'react-grid-HeaderCell-sortable--ascending': this.props.sortDirection === 'ASC',
'react-grid-HeaderCell-sortable--descending': this.props.sortDirection === 'DESC'
});
return React.createElement(
'div',
{ className: className,
onClick: this.onClick,
style: { cursor: 'pointer' } },
this.props.column.name,
React.createElement(
'span',
{ className: 'pull-right' },
this.getSortByText()
)
);
}
});
module.exports = SortableHeaderCell;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ExcelColumn = __webpack_require__(15);
var FilterableHeaderCell = React.createClass({
displayName: 'FilterableHeaderCell',
propTypes: {
onChange: React.PropTypes.func.isRequired,
column: React.PropTypes.shape(ExcelColumn)
},
getInitialState: function getInitialState() {
return { filterTerm: '' };
},
handleChange: function handleChange(e) {
var val = e.target.value;
this.setState({ filterTerm: val });
this.props.onChange({ filterTerm: val, columnKey: this.props.column.key });
},
renderInput: function renderInput() {
if (this.props.column.filterable === false) {
return React.createElement('span', null);
}
var inputKey = 'header-filter-' + this.props.column.key;
return React.createElement('input', { key: inputKey, type: 'text', className: 'form-control input-sm', placeholder: 'Search', value: this.state.filterTerm, onChange: this.handleChange });
},
render: function render() {
return React.createElement(
'div',
null,
React.createElement(
'div',
{ className: 'form-group' },
this.renderInput()
)
);
}
});
module.exports = FilterableHeaderCell;
/***/ },
/* 20 */
/***/ function(module, exports) {
"use strict";
var HeaderCellType = {
SORTABLE: 0,
FILTERABLE: 1,
NONE: 2,
CHECKBOX: 3
};
module.exports = HeaderCellType;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var Canvas = __webpack_require__(22);
var ViewportScroll = __webpack_require__(33);
var cellMetaDataShape = __webpack_require__(31);
var PropTypes = React.PropTypes;
var Viewport = React.createClass({
displayName: 'Viewport',
mixins: [ViewportScroll],
propTypes: {
rowOffsetHeight: PropTypes.number.isRequired,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
columnMetrics: PropTypes.object.isRequired,
rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired,
selectedRows: PropTypes.array,
expandedRows: PropTypes.array,
rowRenderer: PropTypes.func,
rowsCount: PropTypes.number.isRequired,
rowHeight: PropTypes.number.isRequired,
onRows: PropTypes.func,
onScroll: PropTypes.func,
minHeight: PropTypes.number,
cellMetaData: PropTypes.shape(cellMetaDataShape),
rowKey: PropTypes.string.isRequired,
rowScrollTimeout: PropTypes.number
},
onScroll: function onScroll(scroll) {
this.updateScroll(scroll.scrollTop, scroll.scrollLeft, this.state.height, this.props.rowHeight, this.props.rowsCount);
if (this.props.onScroll) {
this.props.onScroll({ scrollTop: scroll.scrollTop, scrollLeft: scroll.scrollLeft });
}
},
getScroll: function getScroll() {
return this.refs.canvas.getScroll();
},
setScrollLeft: function setScrollLeft(scrollLeft) {
this.refs.canvas.setScrollLeft(scrollLeft);
},
render: function render() {
var style = {
padding: 0,
bottom: 0,
left: 0,
right: 0,
overflow: 'hidden',
position: 'absolute',
top: this.props.rowOffsetHeight
};
return React.createElement(
'div',
{
className: 'react-grid-Viewport',
style: style },
React.createElement(Canvas, {
ref: 'canvas',
rowKey: this.props.rowKey,
totalWidth: this.props.totalWidth,
width: this.props.columnMetrics.width,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
selectedRows: this.props.selectedRows,
expandedRows: this.props.expandedRows,
columns: this.props.columnMetrics.columns,
rowRenderer: this.props.rowRenderer,
displayStart: this.state.displayStart,
displayEnd: this.state.displayEnd,
cellMetaData: this.props.cellMetaData,
height: this.state.height,
rowHeight: this.props.rowHeight,
onScroll: this.onScroll,
onRows: this.props.onRows,
rowScrollTimeout: this.props.rowScrollTimeout
})
);
}
});
module.exports = Viewport;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _shallowEqual = __webpack_require__(13);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(3);
var joinClasses = __webpack_require__(6);
var PropTypes = React.PropTypes;
var ScrollShim = __webpack_require__(23);
var Row = __webpack_require__(24);
var cellMetaDataShape = __webpack_require__(31);
var Canvas = React.createClass({
displayName: 'Canvas',
mixins: [ScrollShim],
propTypes: {
rowRenderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
rowHeight: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
width: PropTypes.number,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
style: PropTypes.string,
className: PropTypes.string,
displayStart: PropTypes.number.isRequired,
displayEnd: PropTypes.number.isRequired,
rowsCount: PropTypes.number.isRequired,
rowGetter: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.array.isRequired]),
expandedRows: PropTypes.array,
onRows: PropTypes.func,
onScroll: PropTypes.func,
columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
cellMetaData: PropTypes.shape(cellMetaDataShape).isRequired,
selectedRows: PropTypes.array,
rowKey: React.PropTypes.string,
rowScrollTimeout: React.PropTypes.number
},
getDefaultProps: function getDefaultProps() {
return {
rowRenderer: Row,
onRows: function onRows() {},
selectedRows: [],
rowScrollTimeout: 0
};
},
getInitialState: function getInitialState() {
return {
displayStart: this.props.displayStart,
displayEnd: this.props.displayEnd,
scrollingTimeout: null
};
},
componentWillMount: function componentWillMount() {
this._currentRowsLength = 0;
this._currentRowsRange = { start: 0, end: 0 };
this._scroll = { scrollTop: 0, scrollLeft: 0 };
},
componentDidMount: function componentDidMount() {
this.onRows();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.displayStart !== this.state.displayStart || nextProps.displayEnd !== this.state.displayEnd) {
this.setState({
displayStart: nextProps.displayStart,
displayEnd: nextProps.displayEnd
});
}
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
var shouldUpdate = nextState.displayStart !== this.state.displayStart || nextState.displayEnd !== this.state.displayEnd || nextState.scrollingTimeout !== this.state.scrollingTimeout || nextProps.rowsCount !== this.props.rowsCount || nextProps.rowHeight !== this.props.rowHeight || nextProps.columns !== this.props.columns || nextProps.width !== this.props.width || nextProps.cellMetaData !== this.props.cellMetaData || !(0, _shallowEqual2['default'])(nextProps.style, this.props.style);
return shouldUpdate;
},
componentWillUnmount: function componentWillUnmount() {
this._currentRowsLength = 0;
this._currentRowsRange = { start: 0, end: 0 };
this._scroll = { scrollTop: 0, scrollLeft: 0 };
},
componentDidUpdate: function componentDidUpdate() {
if (this._scroll.scrollTop !== 0 && this._scroll.scrollLeft !== 0) {
this.setScrollLeft(this._scroll.scrollLeft);
}
this.onRows();
},
onRows: function onRows() {
if (this._currentRowsRange !== { start: 0, end: 0 }) {
this.props.onRows(this._currentRowsRange);
this._currentRowsRange = { start: 0, end: 0 };
}
},
onScroll: function onScroll(e) {
var _this = this;
if (this.getDOMNode() !== e.target) {
return;
}
this.appendScrollShim();
var scrollLeft = e.target.scrollLeft;
var scrollTop = e.target.scrollTop || this._scroll.scrollTop;
var scroll = { scrollTop: scrollTop, scrollLeft: scrollLeft };
// check how far we have scrolled, and if this means we are being taken out of range
var scrollYRange = Math.abs(this._scroll.scrollTop - scroll.scrollTop) / this.props.rowHeight;
var scrolledOutOfRange = scrollYRange > this.props.displayEnd - this.props.displayStart;
this._scroll = scroll;
this.props.onScroll(scroll);
// if we go out of range, we queue the actual render, just rendering cheap placeholders
// avoiding rendering anything expensive while a user scrolls down
if (scrolledOutOfRange && this.props.rowScrollTimeout > 0) {
var scrollTO = this.state.scrollingTimeout;
if (scrollTO) {
clearTimeout(scrollTO);
}
// queue up, and set state to clear the TO so we render the rows (not placeholders)
scrollTO = setTimeout(function () {
if (_this.state.scrollingTimeout !== null) {
_this.setState({ scrollingTimeout: null });
}
}, this.props.rowScrollTimeout);
this.setState({ scrollingTimeout: scrollTO });
}
},
getRows: function getRows(displayStart, displayEnd) {
this._currentRowsRange = { start: displayStart, end: displayEnd };
if (Array.isArray(this.props.rowGetter)) {
return this.props.rowGetter.slice(displayStart, displayEnd);
}
var rows = [];
for (var i = displayStart; i < displayEnd; i++) {
rows.push(this.props.rowGetter(i));
}
return rows;
},
getScrollbarWidth: function getScrollbarWidth() {
var scrollbarWidth = 0;
// Get the scrollbar width
var canvas = ReactDOM.findDOMNode(this);
scrollbarWidth = canvas.offsetWidth - canvas.clientWidth;
return scrollbarWidth;
},
getScroll: function getScroll() {
var _ReactDOM$findDOMNode = ReactDOM.findDOMNode(this);
var scrollTop = _ReactDOM$findDOMNode.scrollTop;
var scrollLeft = _ReactDOM$findDOMNode.scrollLeft;
return { scrollTop: scrollTop, scrollLeft: scrollLeft };
},
isRowSelected: function isRowSelected(row) {
var _this2 = this;
var selectedRows = this.props.selectedRows.filter(function (r) {
var rowKeyValue = row.get ? row.get(_this2.props.rowKey) : row[_this2.props.rowKey];
return r[_this2.props.rowKey] === rowKeyValue;
});
return selectedRows.length > 0 && selectedRows[0].isSelected;
},
_currentRowsLength: 0,
_currentRowsRange: { start: 0, end: 0 },
_scroll: { scrollTop: 0, scrollLeft: 0 },
setScrollLeft: function setScrollLeft(scrollLeft) {
if (this._currentRowsLength !== 0) {
if (!this.refs) return;
for (var i = 0, len = this._currentRowsLength; i < len; i++) {
if (this.refs[i] && this.refs[i].setScrollLeft) {
this.refs[i].setScrollLeft(scrollLeft);
}
}
}
},
renderRow: function renderRow(props) {
if (this.state.scrollingTimeout !== null) {
// in the midst of a rapid scroll, so we render placeholders
// the actual render is then queued (through a timeout)
// this avoids us redering a bunch of rows that a user is trying to scroll past
return this.renderScrollingPlaceholder(props);
}
var RowsRenderer = this.props.rowRenderer;
if (typeof RowsRenderer === 'function') {
return React.createElement(RowsRenderer, props);
}
if (React.isValidElement(this.props.rowRenderer)) {
return React.cloneElement(this.props.rowRenderer, props);
}
},
renderScrollingPlaceholder: function renderScrollingPlaceholder(props) {
// here we are just rendering empty cells
// we may want to allow a user to inject this, and/or just render the cells that are in view
// for now though we essentially are doing a (very lightweight) row + cell with empty content
var styles = {
row: { height: props.height, overflow: 'hidden' },
cell: { height: props.height, position: 'absolute' },
placeholder: { backgroundColor: 'rgba(211, 211, 211, 0.45)', width: '60%', height: Math.floor(props.height * 0.3) }
};
return React.createElement(
'div',
{ key: props.key, style: styles.row, className: 'react-grid-Row' },
this.props.columns.map(function (col, idx) {
return React.createElement(
'div',
{ style: Object.assign(styles.cell, { width: col.width, left: col.left }), key: idx, className: 'react-grid-Cell' },
React.createElement('div', { style: Object.assign(styles.placeholder, { width: Math.floor(col.width * 0.6) }) })
);
})
);
},
renderPlaceholder: function renderPlaceholder(key, height) {
// just renders empty cells
// if we wanted to show gridlines, we'd need classes and position as with renderScrollingPlaceholder
return React.createElement(
'div',
{ key: key, style: { height: height } },
this.props.columns.map(function (column, idx) {
return React.createElement('div', { style: { width: column.width }, key: idx });
})
);
},
render: function render() {
var _this3 = this;
var displayStart = this.state.displayStart;
var displayEnd = this.state.displayEnd;
var rowHeight = this.props.rowHeight;
var length = this.props.rowsCount;
var rows = this.getRows(displayStart, displayEnd).map(function (row, idx) {
return _this3.renderRow({
key: displayStart + idx,
ref: idx,
idx: displayStart + idx,
row: row,
height: rowHeight,
columns: _this3.props.columns,
isSelected: _this3.isRowSelected(row),
expandedRows: _this3.props.expandedRows,
cellMetaData: _this3.props.cellMetaData
});
});
this._currentRowsLength = rows.length;
if (displayStart > 0) {
rows.unshift(this.renderPlaceholder('top', displayStart * rowHeight));
}
if (length - displayEnd > 0) {
rows.push(this.renderPlaceholder('bottom', (length - displayEnd) * rowHeight));
}
var style = {
position: 'absolute',
top: 0,
left: 0,
overflowX: 'auto',
overflowY: 'scroll',
width: this.props.totalWidth,
height: this.props.height,
transform: 'translate3d(0, 0, 0)'
};
return React.createElement(
'div',
{
style: style,
onScroll: this.onScroll,
className: joinClasses('react-grid-Canvas', this.props.className, { opaque: this.props.cellMetaData.selected && this.props.cellMetaData.selected.active }) },
React.createElement(
'div',
{ style: { width: this.props.width, overflow: 'hidden' } },
rows
)
);
}
});
module.exports = Canvas;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _reactDom = __webpack_require__(3);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var ScrollShim = {
appendScrollShim: function appendScrollShim() {
if (!this._scrollShim) {
var size = this._scrollShimSize();
var shim = document.createElement('div');
if (shim.classList) {
shim.classList.add('react-grid-ScrollShim'); // flow - not compatible with HTMLElement
} else {
shim.className += ' react-grid-ScrollShim';
}
shim.style.position = 'absolute';
shim.style.top = 0;
shim.style.left = 0;
shim.style.width = size.width + 'px';
shim.style.height = size.height + 'px';
_reactDom2['default'].findDOMNode(this).appendChild(shim);
this._scrollShim = shim;
}
this._scheduleRemoveScrollShim();
},
_scrollShimSize: function _scrollShimSize() {
return {
width: this.props.width,
height: this.props.length * this.props.rowHeight
};
},
_scheduleRemoveScrollShim: function _scheduleRemoveScrollShim() {
if (this._scheduleRemoveScrollShimTimer) {
clearTimeout(this._scheduleRemoveScrollShimTimer);
}
this._scheduleRemoveScrollShimTimer = setTimeout(this._removeScrollShim, 200);
},
_removeScrollShim: function _removeScrollShim() {
if (this._scrollShim) {
this._scrollShim.parentNode.removeChild(this._scrollShim);
this._scrollShim = undefined;
}
}
};
module.exports = ScrollShim;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(2);
var joinClasses = __webpack_require__(6);
var Cell = __webpack_require__(25);
var ColumnMetrics = __webpack_require__(8);
var ColumnUtilsMixin = __webpack_require__(10);
var cellMetaDataShape = __webpack_require__(31);
var PropTypes = React.PropTypes;
var Row = React.createClass({
displayName: 'Row',
propTypes: {
height: PropTypes.number.isRequired,
columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
row: PropTypes.any.isRequired,
cellRenderer: PropTypes.func,
cellMetaData: PropTypes.shape(cellMetaDataShape),
isSelected: PropTypes.bool,
idx: PropTypes.number.isRequired,
key: PropTypes.string,
expandedRows: PropTypes.arrayOf(PropTypes.object)
},
mixins: [ColumnUtilsMixin],
getDefaultProps: function getDefaultProps() {
return {
cellRenderer: Cell,
isSelected: false,
height: 35
};
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return !ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, ColumnMetrics.sameColumn) || this.doesRowContainSelectedCell(this.props) || this.doesRowContainSelectedCell(nextProps) || this.willRowBeDraggedOver(nextProps) || nextProps.row !== this.props.row || this.hasRowBeenCopied() || this.props.isSelected !== nextProps.isSelected || nextProps.height !== this.props.height;
},
handleDragEnter: function handleDragEnter() {
var handleDragEnterRow = this.props.cellMetaData.handleDragEnterRow;
if (handleDragEnterRow) {
handleDragEnterRow(this.props.idx);
}
},
getSelectedColumn: function getSelectedColumn() {
var selected = this.props.cellMetaData.selected;
if (selected && selected.idx) {
return this.getColumn(this.props.columns, selected.idx);
}
},
getCells: function getCells() {
var _this = this;
var cells = [];
var lockedCells = [];
var selectedColumn = this.getSelectedColumn();
this.props.columns.forEach(function (column, i) {
var CellRenderer = _this.props.cellRenderer;
var cell = React.createElement(CellRenderer, {
ref: i,
key: column.key + '-' + i,
idx: i,
rowIdx: _this.props.idx,
value: _this.getCellValue(column.key || i),
column: column,
height: _this.getRowHeight(),
formatter: column.formatter,
cellMetaData: _this.props.cellMetaData,
rowData: _this.props.row,
selectedColumn: selectedColumn,
isRowSelected: _this.props.isSelected });
if (column.locked) {
lockedCells.push(cell);
} else {
cells.push(cell);
}
});
return cells.concat(lockedCells);
},
getRowHeight: function getRowHeight() {
var rows = this.props.expandedRows || null;
if (rows && this.props.key) {
var row = rows[this.props.key] || null;
if (row) {
return row.height;
}
}
return this.props.height;
},
getCellValue: function getCellValue(key) {
var val = void 0;
if (key === 'select-row') {
return this.props.isSelected;
} else if (typeof this.props.row.get === 'function') {
val = this.props.row.get(key);
} else {
val = this.props.row[key];
}
return val;
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var _this2 = this;
this.props.columns.forEach(function (column, i) {
if (column.locked) {
if (!_this2.refs[i]) return;
_this2.refs[i].setScrollLeft(scrollLeft);
}
});
},
doesRowContainSelectedCell: function doesRowContainSelectedCell(props) {
var selected = props.cellMetaData.selected;
if (selected && selected.rowIdx === props.idx) {
return true;
}
return false;
},
willRowBeDraggedOver: function willRowBeDraggedOver(props) {
var dragged = props.cellMetaData.dragged;
return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true);
},
hasRowBeenCopied: function hasRowBeenCopied() {
var copied = this.props.cellMetaData.copied;
return copied != null && copied.rowIdx === this.props.idx;
},
renderCell: function renderCell(props) {
if (typeof this.props.cellRenderer === 'function') {
this.props.cellRenderer.call(this, props);
}
if (React.isValidElement(this.props.cellRenderer)) {
return React.cloneElement(this.props.cellRenderer, props);
}
return this.props.cellRenderer(props);
},
render: function render() {
var className = joinClasses('react-grid-Row', 'react-grid-Row--' + (this.props.idx % 2 === 0 ? 'even' : 'odd'), { 'row-selected': this.props.isSelected });
var style = {
height: this.getRowHeight(this.props),
overflow: 'hidden'
};
var cells = this.getCells();
return React.createElement(
'div',
_extends({}, this.props, { className: className, style: style, onDragEnter: this.handleDragEnter }),
React.isValidElement(this.props.row) ? this.props.row : cells
);
}
});
module.exports = Row;
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(3);
var joinClasses = __webpack_require__(6);
var EditorContainer = __webpack_require__(26);
var ExcelColumn = __webpack_require__(15);
var isFunction = __webpack_require__(30);
var CellMetaDataShape = __webpack_require__(31);
var SimpleCellFormatter = __webpack_require__(32);
var Cell = React.createClass({
displayName: 'Cell',
propTypes: {
rowIdx: React.PropTypes.number.isRequired,
idx: React.PropTypes.number.isRequired,
selected: React.PropTypes.shape({
idx: React.PropTypes.number.isRequired
}),
selectedColumn: React.PropTypes.object,
height: React.PropTypes.number,
tabIndex: React.PropTypes.number,
ref: React.PropTypes.string,
column: React.PropTypes.shape(ExcelColumn).isRequired,
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired,
isExpanded: React.PropTypes.bool,
isRowSelected: React.PropTypes.bool,
cellMetaData: React.PropTypes.shape(CellMetaDataShape).isRequired,
handleDragStart: React.PropTypes.func,
className: React.PropTypes.string,
cellControls: React.PropTypes.any,
rowData: React.PropTypes.object.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
tabIndex: -1,
ref: 'cell',
isExpanded: false
};
},
getInitialState: function getInitialState() {
return { isRowChanging: false, isCellValueChanging: false };
},
componentDidMount: function componentDidMount() {
this.checkFocus();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.setState({ isRowChanging: this.props.rowData !== nextProps.rowData, isCellValueChanging: this.props.value !== nextProps.value });
},
componentDidUpdate: function componentDidUpdate() {
this.checkFocus();
var dragged = this.props.cellMetaData.dragged;
if (dragged && dragged.complete === true) {
this.props.cellMetaData.handleTerminateDrag();
}
if (this.state.isRowChanging && this.props.selectedColumn != null) {
this.applyUpdateClass();
}
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.rowData !== nextProps.rowData || this.props.height !== nextProps.height || this.props.rowIdx !== nextProps.rowIdx || this.isCellSelectionChanging(nextProps) || this.isDraggedCellChanging(nextProps) || this.isCopyCellChanging(nextProps) || this.props.isRowSelected !== nextProps.isRowSelected || this.isSelected() || this.props.value !== nextProps.value;
},
onCellClick: function onCellClick() {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellClick != null) {
meta.onCellClick({ rowIdx: this.props.rowIdx, idx: this.props.idx });
}
},
onCellDoubleClick: function onCellDoubleClick() {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellDoubleClick != null) {
meta.onCellDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx });
}
},
onDragHandleDoubleClick: function onDragHandleDoubleClick(e) {
e.stopPropagation();
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellDoubleClick != null) {
meta.onDragHandleDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx, rowData: this.getRowData() });
}
},
onDragOver: function onDragOver(e) {
e.preventDefault();
},
getStyle: function getStyle() {
var style = {
position: 'absolute',
width: this.props.column.width,
height: this.props.height,
left: this.props.column.left
};
return style;
},
getFormatter: function getFormatter() {
var col = this.props.column;
if (this.isActive()) {
return React.createElement(EditorContainer, { rowData: this.getRowData(), rowIdx: this.props.rowIdx, idx: this.props.idx, cellMetaData: this.props.cellMetaData, column: col, height: this.props.height });
}
return this.props.column.formatter;
},
getRowData: function getRowData() {
return this.props.rowData.toJSON ? this.props.rowData.toJSON() : this.props.rowData;
},
getFormatterDependencies: function getFormatterDependencies() {
// convention based method to get corresponding Id or Name of any Name or Id property
if (typeof this.props.column.getRowMetaData === 'function') {
return this.props.column.getRowMetaData(this.getRowData(), this.props.column);
}
},
getCellClass: function getCellClass() {
var className = joinClasses(this.props.column.cellClass, 'react-grid-Cell', this.props.className, this.props.column.locked ? 'react-grid-Cell--locked' : null);
var extraClasses = joinClasses({
'row-selected': this.props.isRowSelected,
selected: this.isSelected() && !this.isActive(),
editing: this.isActive(),
copied: this.isCopied() || this.wasDraggedOver() || this.isDraggedOverUpwards() || this.isDraggedOverDownwards(),
'active-drag-cell': this.isSelected() || this.isDraggedOver(),
'is-dragged-over-up': this.isDraggedOverUpwards(),
'is-dragged-over-down': this.isDraggedOverDownwards(),
'was-dragged-over': this.wasDraggedOver()
});
return joinClasses(className, extraClasses);
},
getUpdateCellClass: function getUpdateCellClass() {
return this.props.column.getUpdateCellClass ? this.props.column.getUpdateCellClass(this.props.selectedColumn, this.props.column, this.state.isCellValueChanging) : '';
},
isColumnSelected: function isColumnSelected() {
var meta = this.props.cellMetaData;
if (meta == null || meta.selected == null) {
return false;
}
return meta.selected && meta.selected.idx === this.props.idx;
},
isSelected: function isSelected() {
var meta = this.props.cellMetaData;
if (meta == null || meta.selected == null) {
return false;
}
return meta.selected && meta.selected.rowIdx === this.props.rowIdx && meta.selected.idx === this.props.idx;
},
isActive: function isActive() {
var meta = this.props.cellMetaData;
if (meta == null || meta.selected == null) {
return false;
}
return this.isSelected() && meta.selected.active === true;
},
isCellSelectionChanging: function isCellSelectionChanging(nextProps) {
var meta = this.props.cellMetaData;
if (meta == null || meta.selected == null) {
return false;
}
var nextSelected = nextProps.cellMetaData.selected;
if (meta.selected && nextSelected) {
return this.props.idx === nextSelected.idx || this.props.idx === meta.selected.idx;
}
return true;
},
applyUpdateClass: function applyUpdateClass() {
var updateCellClass = this.getUpdateCellClass();
// -> removing the class
if (updateCellClass != null && updateCellClass !== '') {
var cellDOMNode = ReactDOM.findDOMNode(this);
if (cellDOMNode.classList) {
cellDOMNode.classList.remove(updateCellClass);
// -> and re-adding the class
cellDOMNode.classList.add(updateCellClass);
} else if (cellDOMNode.className.indexOf(updateCellClass) === -1) {
// IE9 doesn't support classList, nor (I think) altering element.className
// without replacing it wholesale.
cellDOMNode.className = cellDOMNode.className + ' ' + updateCellClass;
}
}
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var ctrl = this; // flow on windows has an outdated react declaration, once that gets updated, we can remove this
if (ctrl.isMounted()) {
var node = ReactDOM.findDOMNode(this);
var transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
node.style.webkitTransform = transform;
node.style.transform = transform;
}
},
isCopied: function isCopied() {
var copied = this.props.cellMetaData.copied;
return copied && copied.rowIdx === this.props.rowIdx && copied.idx === this.props.idx;
},
isDraggedOver: function isDraggedOver() {
var dragged = this.props.cellMetaData.dragged;
return dragged && dragged.overRowIdx === this.props.rowIdx && dragged.idx === this.props.idx;
},
wasDraggedOver: function wasDraggedOver() {
var dragged = this.props.cellMetaData.dragged;
return dragged && (dragged.overRowIdx < this.props.rowIdx && this.props.rowIdx < dragged.rowIdx || dragged.overRowIdx > this.props.rowIdx && this.props.rowIdx > dragged.rowIdx) && dragged.idx === this.props.idx;
},
isDraggedCellChanging: function isDraggedCellChanging(nextProps) {
var isChanging = void 0;
var dragged = this.props.cellMetaData.dragged;
var nextDragged = nextProps.cellMetaData.dragged;
if (dragged) {
isChanging = nextDragged && this.props.idx === nextDragged.idx || dragged && this.props.idx === dragged.idx;
return isChanging;
}
return false;
},
isCopyCellChanging: function isCopyCellChanging(nextProps) {
var isChanging = void 0;
var copied = this.props.cellMetaData.copied;
var nextCopied = nextProps.cellMetaData.copied;
if (copied) {
isChanging = nextCopied && this.props.idx === nextCopied.idx || copied && this.props.idx === copied.idx;
return isChanging;
}
return false;
},
isDraggedOverUpwards: function isDraggedOverUpwards() {
var dragged = this.props.cellMetaData.dragged;
return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx < dragged.rowIdx;
},
isDraggedOverDownwards: function isDraggedOverDownwards() {
var dragged = this.props.cellMetaData.dragged;
return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx > dragged.rowIdx;
},
checkFocus: function checkFocus() {
if (this.isSelected() && !this.isActive()) {
// determine the parent viewport element of this cell
var parentViewport = ReactDOM.findDOMNode(this);
while (parentViewport != null && parentViewport.className.indexOf('react-grid-Viewport') === -1) {
parentViewport = parentViewport.parentElement;
}
var focusInGrid = false;
// if the focus is on the body of the document, the user won't mind if we focus them on a cell
if (document.activeElement == null || document.activeElement.nodeName && typeof document.activeElement.nodeName === 'string' && document.activeElement.nodeName.toLowerCase() === 'body') {
focusInGrid = true;
// otherwise
} else {
// only pull focus if the currently focused element is contained within the viewport
if (parentViewport) {
var focusedParent = document.activeElement;
while (focusedParent != null) {
if (focusedParent === parentViewport) {
focusInGrid = true;
break;
}
focusedParent = focusedParent.parentElement;
}
}
}
if (focusInGrid) {
ReactDOM.findDOMNode(this).focus();
}
}
},
canEdit: function canEdit() {
return this.props.column.editor != null || this.props.column.editable;
},
renderCellContent: function renderCellContent(props) {
var CellContent = void 0;
var Formatter = this.getFormatter();
if (React.isValidElement(Formatter)) {
props.dependentValues = this.getFormatterDependencies();
CellContent = React.cloneElement(Formatter, props);
} else if (isFunction(Formatter)) {
CellContent = React.createElement(Formatter, { value: this.props.value, dependentValues: this.getFormatterDependencies() });
} else {
CellContent = React.createElement(SimpleCellFormatter, { value: this.props.value });
}
return React.createElement(
'div',
{ ref: 'cell',
className: 'react-grid-Cell__value' },
CellContent,
' ',
this.props.cellControls
);
},
render: function render() {
var style = this.getStyle();
var className = this.getCellClass();
var cellContent = this.renderCellContent({
value: this.props.value,
column: this.props.column,
rowIdx: this.props.rowIdx,
isExpanded: this.props.isExpanded
});
var dragHandle = !this.isActive() && this.canEdit() ? React.createElement(
'div',
{ className: 'drag-handle', draggable: 'true', onDoubleClick: this.onDragHandleDoubleClick },
React.createElement('span', { style: { display: 'none' } })
) : null;
return React.createElement(
'div',
_extends({}, this.props, { className: className, style: style, onClick: this.onCellClick, onDoubleClick: this.onCellDoubleClick, onDragOver: this.onDragOver }),
cellContent,
dragHandle
);
}
});
module.exports = Cell;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var joinClasses = __webpack_require__(6);
var keyboardHandlerMixin = __webpack_require__(27);
var SimpleTextEditor = __webpack_require__(28);
var isFunction = __webpack_require__(30);
var EditorContainer = React.createClass({
displayName: 'EditorContainer',
mixins: [keyboardHandlerMixin],
propTypes: {
rowIdx: React.PropTypes.number,
rowData: React.PropTypes.object.isRequired,
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired,
cellMetaData: React.PropTypes.shape({
selected: React.PropTypes.object.isRequired,
copied: React.PropTypes.object,
dragged: React.PropTypes.object,
onCellClick: React.PropTypes.func,
onCellDoubleClick: React.PropTypes.func,
onCommitCancel: React.PropTypes.func,
onCommit: React.PropTypes.func
}).isRequired,
column: React.PropTypes.object.isRequired,
height: React.PropTypes.number.isRequired
},
changeCommitted: false,
getInitialState: function getInitialState() {
return { isInvalid: false };
},
componentDidMount: function componentDidMount() {
var inputNode = this.getInputNode();
if (inputNode !== undefined) {
this.setTextInputFocus();
if (!this.getEditor().disableContainerStyles) {
inputNode.className += ' editor-main';
inputNode.style.height = this.props.height - 1 + 'px';
}
}
},
componentWillUnmount: function componentWillUnmount() {
if (!this.changeCommitted && !this.hasEscapeBeenPressed()) {
this.commit({ key: 'Enter' });
}
},
createEditor: function createEditor() {
var _this = this;
var editorRef = function editorRef(c) {
return _this.editor = c;
};
var editorProps = {
ref: editorRef,
column: this.props.column,
value: this.getInitialValue(),
onCommit: this.commit,
rowMetaData: this.getRowMetaData(),
height: this.props.height,
onBlur: this.commit,
onOverrideKeyDown: this.onKeyDown
};
var customEditor = this.props.column.editor;
if (customEditor && React.isValidElement(customEditor)) {
// return custom column editor or SimpleEditor if none specified
return React.cloneElement(customEditor, editorProps);
}
return React.createElement(SimpleTextEditor, { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onBlur: this.commit, rowMetaData: this.getRowMetaData(), onKeyDown: function onKeyDown() {}, commit: function commit() {} });
},
onPressEnter: function onPressEnter() {
this.commit({ key: 'Enter' });
},
onPressTab: function onPressTab() {
this.commit({ key: 'Tab' });
},
onPressEscape: function onPressEscape(e) {
if (!this.editorIsSelectOpen()) {
this.props.cellMetaData.onCommitCancel();
} else {
// prevent event from bubbling if editor has results to select
e.stopPropagation();
}
},
onPressArrowDown: function onPressArrowDown(e) {
if (this.editorHasResults()) {
// dont want to propogate as that then moves us round the grid
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowUp: function onPressArrowUp(e) {
if (this.editorHasResults()) {
// dont want to propogate as that then moves us round the grid
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowLeft: function onPressArrowLeft(e) {
// prevent event propogation. this disables left cell navigation
if (!this.isCaretAtBeginningOfInput()) {
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowRight: function onPressArrowRight(e) {
// prevent event propogation. this disables right cell navigation
if (!this.isCaretAtEndOfInput()) {
e.stopPropagation();
} else {
this.commit(e);
}
},
editorHasResults: function editorHasResults() {
if (isFunction(this.getEditor().hasResults)) {
return this.getEditor().hasResults();
}
return false;
},
editorIsSelectOpen: function editorIsSelectOpen() {
if (isFunction(this.getEditor().isSelectOpen)) {
return this.getEditor().isSelectOpen();
}
return false;
},
getRowMetaData: function getRowMetaData() {
// clone row data so editor cannot actually change this
// convention based method to get corresponding Id or Name of any Name or Id property
if (typeof this.props.column.getRowMetaData === 'function') {
return this.props.column.getRowMetaData(this.props.rowData, this.props.column);
}
},
getEditor: function getEditor() {
return this.editor;
},
getInputNode: function getInputNode() {
return this.getEditor().getInputNode();
},
getInitialValue: function getInitialValue() {
var selected = this.props.cellMetaData.selected;
var keyCode = selected.initialKeyCode;
if (keyCode === 'Delete' || keyCode === 'Backspace') {
return '';
} else if (keyCode === 'Enter') {
return this.props.value;
}
var text = keyCode ? String.fromCharCode(keyCode) : this.props.value;
return text;
},
getContainerClass: function getContainerClass() {
return joinClasses({
'has-error': this.state.isInvalid === true
});
},
commit: function commit(args) {
var opts = args || {};
var updated = this.getEditor().getValue();
if (this.isNewValueValid(updated)) {
this.changeCommitted = true;
var cellKey = this.props.column.key;
this.props.cellMetaData.onCommit({ cellKey: cellKey, rowIdx: this.props.rowIdx, updated: updated, key: opts.key });
}
},
isNewValueValid: function isNewValueValid(value) {
if (isFunction(this.getEditor().validate)) {
var isValid = this.getEditor().validate(value);
this.setState({ isInvalid: !isValid });
return isValid;
}
return true;
},
setCaretAtEndOfInput: function setCaretAtEndOfInput() {
var input = this.getInputNode();
// taken from http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element
var txtLength = input.value.length;
if (input.setSelectionRange) {
input.setSelectionRange(txtLength, txtLength);
} else if (input.createTextRange) {
var fieldRange = input.createTextRange();
fieldRange.moveStart('character', txtLength);
fieldRange.collapse();
fieldRange.select();
}
},
isCaretAtBeginningOfInput: function isCaretAtBeginningOfInput() {
var inputNode = this.getInputNode();
return inputNode.selectionStart === inputNode.selectionEnd && inputNode.selectionStart === 0;
},
isCaretAtEndOfInput: function isCaretAtEndOfInput() {
var inputNode = this.getInputNode();
return inputNode.selectionStart === inputNode.value.length;
},
setTextInputFocus: function setTextInputFocus() {
var selected = this.props.cellMetaData.selected;
var keyCode = selected.initialKeyCode;
var inputNode = this.getInputNode();
inputNode.focus();
if (inputNode.tagName === 'INPUT') {
if (!this.isKeyPrintable(keyCode)) {
inputNode.focus();
inputNode.select();
} else {
inputNode.select();
}
}
},
hasEscapeBeenPressed: function hasEscapeBeenPressed() {
var pressed = false;
var escapeKey = 27;
if (window.event) {
if (window.event.keyCode === escapeKey) {
pressed = true;
} else if (window.event.which === escapeKey) {
pressed = true;
}
}
return pressed;
},
renderStatusIcon: function renderStatusIcon() {
if (this.state.isInvalid === true) {
return React.createElement('span', { className: 'glyphicon glyphicon-remove form-control-feedback' });
}
},
render: function render() {
return React.createElement(
'div',
{ className: this.getContainerClass(), onKeyDown: this.onKeyDown, commit: this.commit },
this.createEditor(),
this.renderStatusIcon()
);
}
});
module.exports = EditorContainer;
/***/ },
/* 27 */
/***/ function(module, exports) {
'use strict';
var KeyboardHandlerMixin = {
onKeyDown: function onKeyDown(e) {
if (this.isCtrlKeyHeldDown(e)) {
this.checkAndCall('onPressKeyWithCtrl', e);
} else if (this.isKeyExplicitlyHandled(e.key)) {
// break up individual keyPress events to have their own specific callbacks
// this allows multiple mixins to listen to onKeyDown events and somewhat reduces methodName clashing
var callBack = 'onPress' + e.key;
this.checkAndCall(callBack, e);
} else if (this.isKeyPrintable(e.keyCode)) {
this.checkAndCall('onPressChar', e);
}
},
// taken from http://stackoverflow.com/questions/12467240/determine-if-javascript-e-keycode-is-a-printable-non-control-character
isKeyPrintable: function isKeyPrintable(keycode) {
var valid = keycode > 47 && keycode < 58 || // number keys
keycode === 32 || keycode === 13 || // spacebar & return key(s) (if you want to allow carriage returns)
keycode > 64 && keycode < 91 || // letter keys
keycode > 95 && keycode < 112 || // numpad keys
keycode > 185 && keycode < 193 || // ;=,-./` (in order)
keycode > 218 && keycode < 223; // [\]' (in order)
return valid;
},
isKeyExplicitlyHandled: function isKeyExplicitlyHandled(key) {
return typeof this['onPress' + key] === 'function';
},
isCtrlKeyHeldDown: function isCtrlKeyHeldDown(e) {
return e.ctrlKey === true && e.key !== 'Control';
},
checkAndCall: function checkAndCall(methodName, args) {
if (typeof this[methodName] === 'function') {
this[methodName](args);
}
}
};
module.exports = KeyboardHandlerMixin;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = __webpack_require__(2);
var EditorBase = __webpack_require__(29);
var SimpleTextEditor = function (_EditorBase) {
_inherits(SimpleTextEditor, _EditorBase);
function SimpleTextEditor() {
_classCallCheck(this, SimpleTextEditor);
return _possibleConstructorReturn(this, Object.getPrototypeOf(SimpleTextEditor).apply(this, arguments));
}
_createClass(SimpleTextEditor, [{
key: 'render',
value: function render() {
return React.createElement('input', { ref: 'input', type: 'text', onBlur: this.props.onBlur, className: 'form-control', defaultValue: this.props.value });
}
}]);
return SimpleTextEditor;
}(EditorBase);
module.exports = SimpleTextEditor;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(3);
var ExcelColumn = __webpack_require__(15);
var EditorBase = function (_React$Component) {
_inherits(EditorBase, _React$Component);
function EditorBase() {
_classCallCheck(this, EditorBase);
return _possibleConstructorReturn(this, Object.getPrototypeOf(EditorBase).apply(this, arguments));
}
_createClass(EditorBase, [{
key: 'getStyle',
value: function getStyle() {
return {
width: '100%'
};
}
}, {
key: 'getValue',
value: function getValue() {
var updated = {};
updated[this.props.column.key] = this.getInputNode().value;
return updated;
}
}, {
key: 'getInputNode',
value: function getInputNode() {
var domNode = ReactDOM.findDOMNode(this);
if (domNode.tagName === 'INPUT') {
return domNode;
}
return domNode.querySelector('input:not([type=hidden])');
}
}, {
key: 'inheritContainerStyles',
value: function inheritContainerStyles() {
return true;
}
}]);
return EditorBase;
}(React.Component);
EditorBase.propTypes = {
onKeyDown: React.PropTypes.func.isRequired,
value: React.PropTypes.any.isRequired,
onBlur: React.PropTypes.func.isRequired,
column: React.PropTypes.shape(ExcelColumn).isRequired,
commit: React.PropTypes.func.isRequired
};
module.exports = EditorBase;
/***/ },
/* 30 */
/***/ function(module, exports) {
'use strict';
var isFunction = function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
};
module.exports = isFunction;
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var PropTypes = __webpack_require__(2).PropTypes;
module.exports = {
selected: PropTypes.object.isRequired,
copied: PropTypes.object,
dragged: PropTypes.object,
onCellClick: PropTypes.func.isRequired,
onCellDoubleClick: PropTypes.func.isRequired,
onCommit: PropTypes.func.isRequired,
onCommitCancel: PropTypes.func.isRequired,
handleDragEnterRow: PropTypes.func.isRequired,
handleTerminateDrag: PropTypes.func.isRequired
};
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var SimpleCellFormatter = React.createClass({
displayName: 'SimpleCellFormatter',
propTypes: {
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return nextProps.value !== this.props.value;
},
render: function render() {
return React.createElement(
'div',
{ title: this.props.value },
this.props.value
);
}
});
module.exports = SimpleCellFormatter;
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(3);
var DOMMetrics = __webpack_require__(34);
var min = Math.min;
var max = Math.max;
var floor = Math.floor;
var ceil = Math.ceil;
module.exports = {
mixins: [DOMMetrics.MetricsMixin],
DOMMetrics: {
viewportHeight: function viewportHeight() {
return ReactDOM.findDOMNode(this).offsetHeight;
}
},
propTypes: {
rowHeight: React.PropTypes.number,
rowsCount: React.PropTypes.number.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
rowHeight: 30
};
},
getInitialState: function getInitialState() {
return this.getGridState(this.props);
},
getGridState: function getGridState(props) {
var renderedRowsCount = ceil((props.minHeight - props.rowHeight) / props.rowHeight);
var totalRowCount = min(renderedRowsCount * 2, props.rowsCount);
return {
displayStart: 0,
displayEnd: totalRowCount,
height: props.minHeight,
scrollTop: 0,
scrollLeft: 0
};
},
updateScroll: function updateScroll(scrollTop, scrollLeft, height, rowHeight, length) {
var renderedRowsCount = ceil(height / rowHeight);
var visibleStart = floor(scrollTop / rowHeight);
var visibleEnd = min(visibleStart + renderedRowsCount, length);
var displayStart = max(0, visibleStart - renderedRowsCount * 2);
var displayEnd = min(visibleStart + renderedRowsCount * 2, length);
var nextScrollState = {
visibleStart: visibleStart,
visibleEnd: visibleEnd,
displayStart: displayStart,
displayEnd: displayEnd,
height: height,
scrollTop: scrollTop,
scrollLeft: scrollLeft
};
this.setState(nextScrollState);
},
metricsUpdated: function metricsUpdated() {
var height = this.DOMMetrics.viewportHeight();
if (height) {
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, height, this.props.rowHeight, this.props.rowsCount);
}
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (this.props.rowHeight !== nextProps.rowHeight || this.props.minHeight !== nextProps.minHeight) {
this.setState(this.getGridState(nextProps));
} else if (this.props.rowsCount !== nextProps.rowsCount) {
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height, nextProps.rowHeight, nextProps.rowsCount);
// Added to fix the hiding of the bottom scrollbar when showing the filters.
} else if (this.props.rowOffsetHeight !== nextProps.rowOffsetHeight) {
// The value of height can be positive or negative and will be added to the current height to cater for changes in the header height (due to the filer)
var _height = this.props.rowOffsetHeight - nextProps.rowOffsetHeight;
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height + _height, nextProps.rowHeight, nextProps.rowsCount);
}
}
};
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var shallowCloneObject = __webpack_require__(7);
var contextTypes = {
metricsComputator: React.PropTypes.object
};
var MetricsComputatorMixin = {
childContextTypes: contextTypes,
getChildContext: function getChildContext() {
return { metricsComputator: this };
},
getMetricImpl: function getMetricImpl(name) {
return this._DOMMetrics.metrics[name].value;
},
registerMetricsImpl: function registerMetricsImpl(component, metrics) {
var getters = {};
var s = this._DOMMetrics;
for (var name in metrics) {
if (s.metrics[name] !== undefined) {
throw new Error('DOM metric ' + name + ' is already defined');
}
s.metrics[name] = { component: component, computator: metrics[name].bind(component) };
getters[name] = this.getMetricImpl.bind(null, name);
}
if (s.components.indexOf(component) === -1) {
s.components.push(component);
}
return getters;
},
unregisterMetricsFor: function unregisterMetricsFor(component) {
var s = this._DOMMetrics;
var idx = s.components.indexOf(component);
if (idx > -1) {
s.components.splice(idx, 1);
var name = void 0;
var metricsToDelete = {};
for (name in s.metrics) {
if (s.metrics[name].component === component) {
metricsToDelete[name] = true;
}
}
for (name in metricsToDelete) {
if (metricsToDelete.hasOwnProperty(name)) {
delete s.metrics[name];
}
}
}
},
updateMetrics: function updateMetrics() {
var s = this._DOMMetrics;
var needUpdate = false;
for (var name in s.metrics) {
if (!s.metrics.hasOwnProperty(name)) continue;
var newMetric = s.metrics[name].computator();
if (newMetric !== s.metrics[name].value) {
needUpdate = true;
}
s.metrics[name].value = newMetric;
}
if (needUpdate) {
for (var i = 0, len = s.components.length; i < len; i++) {
if (s.components[i].metricsUpdated) {
s.components[i].metricsUpdated();
}
}
}
},
componentWillMount: function componentWillMount() {
this._DOMMetrics = {
metrics: {},
components: []
};
},
componentDidMount: function componentDidMount() {
if (window.addEventListener) {
window.addEventListener('resize', this.updateMetrics);
} else {
window.attachEvent('resize', this.updateMetrics);
}
this.updateMetrics();
},
componentWillUnmount: function componentWillUnmount() {
window.removeEventListener('resize', this.updateMetrics);
}
};
var MetricsMixin = {
contextTypes: contextTypes,
componentWillMount: function componentWillMount() {
if (this.DOMMetrics) {
this._DOMMetricsDefs = shallowCloneObject(this.DOMMetrics);
this.DOMMetrics = {};
for (var name in this._DOMMetricsDefs) {
if (!this._DOMMetricsDefs.hasOwnProperty(name)) continue;
this.DOMMetrics[name] = function () {};
}
}
},
componentDidMount: function componentDidMount() {
if (this.DOMMetrics) {
this.DOMMetrics = this.registerMetrics(this._DOMMetricsDefs);
}
},
componentWillUnmount: function componentWillUnmount() {
if (!this.registerMetricsImpl) {
return this.context.metricsComputator.unregisterMetricsFor(this);
}
if (this.hasOwnProperty('DOMMetrics')) {
delete this.DOMMetrics;
}
},
registerMetrics: function registerMetrics(metrics) {
if (this.registerMetricsImpl) {
return this.registerMetricsImpl(this, metrics);
}
return this.context.metricsComputator.registerMetricsImpl(this, metrics);
},
getMetric: function getMetric(name) {
if (this.getMetricImpl) {
return this.getMetricImpl(name);
}
return this.context.metricsComputator.getMetricImpl(name);
}
};
module.exports = {
MetricsComputatorMixin: MetricsComputatorMixin,
MetricsMixin: MetricsMixin
};
/***/ },
/* 35 */
/***/ function(module, exports) {
"use strict";
module.exports = {
componentDidMount: function componentDidMount() {
this._scrollLeft = this.refs.viewport ? this.refs.viewport.getScroll().scrollLeft : 0;
this._onScroll();
},
componentDidUpdate: function componentDidUpdate() {
this._onScroll();
},
componentWillMount: function componentWillMount() {
this._scrollLeft = undefined;
},
componentWillUnmount: function componentWillUnmount() {
this._scrollLeft = undefined;
},
onScroll: function onScroll(props) {
if (this._scrollLeft !== props.scrollLeft) {
this._scrollLeft = props.scrollLeft;
this._onScroll();
}
},
onHeaderScroll: function onHeaderScroll(e) {
var scrollLeft = e.target.scrollLeft;
if (this._scrollLeft !== scrollLeft) {
this._scrollLeft = scrollLeft;
this.refs.header.setScrollLeft(scrollLeft);
var canvas = ReactDOM.findDOMNode(this.refs.viewport.refs.canvas);
canvas.scrollLeft = scrollLeft;
this.refs.viewport.refs.canvas.setScrollLeft(scrollLeft);
}
},
_onScroll: function _onScroll() {
if (this._scrollLeft !== undefined) {
this.refs.header.setScrollLeft(this._scrollLeft);
if (this.refs.viewport) {
this.refs.viewport.setScrollLeft(this._scrollLeft);
}
}
}
};
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var CheckboxEditor = React.createClass({
displayName: 'CheckboxEditor',
propTypes: {
value: React.PropTypes.bool,
rowIdx: React.PropTypes.number,
column: React.PropTypes.shape({
key: React.PropTypes.string,
onCellChange: React.PropTypes.func
}),
dependentValues: React.PropTypes.object
},
handleChange: function handleChange(e) {
this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, this.props.dependentValues, e);
},
render: function render() {
var checked = this.props.value != null ? this.props.value : false;
var checkboxName = 'checkbox' + this.props.rowIdx;
return React.createElement(
'div',
{ className: 'react-grid-checkbox-container', onClick: this.handleChange },
React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: checkboxName, checked: checked }),
React.createElement('label', { htmlFor: checkboxName, className: 'react-grid-checkbox-label' })
);
}
});
module.exports = CheckboxEditor;
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _reactDom = __webpack_require__(3);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ColumnMetrics = __webpack_require__(8);
var DOMMetrics = __webpack_require__(34);
Object.assign = __webpack_require__(38);
var PropTypes = __webpack_require__(2).PropTypes;
var ColumnUtils = __webpack_require__(10);
var Column = function Column() {
_classCallCheck(this, Column);
};
module.exports = {
mixins: [DOMMetrics.MetricsMixin],
propTypes: {
columns: PropTypes.arrayOf(Column),
minColumnWidth: PropTypes.number,
columnEquality: PropTypes.func
},
DOMMetrics: {
gridWidth: function gridWidth() {
return _reactDom2['default'].findDOMNode(this).parentElement.offsetWidth;
}
},
getDefaultProps: function getDefaultProps() {
return {
minColumnWidth: 80,
columnEquality: ColumnMetrics.sameColumn
};
},
componentWillMount: function componentWillMount() {
this._mounted = true;
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.columns) {
if (!ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, this.props.columnEquality) || nextProps.minWidth !== this.props.minWidth) {
var columnMetrics = this.createColumnMetrics(nextProps);
this.setState({ columnMetrics: columnMetrics });
}
}
},
getTotalWidth: function getTotalWidth() {
var totalWidth = 0;
if (this._mounted) {
totalWidth = this.DOMMetrics.gridWidth();
} else {
totalWidth = ColumnUtils.getSize(this.props.columns) * this.props.minColumnWidth;
}
return totalWidth;
},
getColumnMetricsType: function getColumnMetricsType(metrics) {
var totalWidth = metrics.totalWidth || this.getTotalWidth();
var currentMetrics = {
columns: metrics.columns,
totalWidth: totalWidth,
minColumnWidth: metrics.minColumnWidth
};
var updatedMetrics = ColumnMetrics.recalculate(currentMetrics);
return updatedMetrics;
},
getColumn: function getColumn(idx) {
var columns = this.state.columnMetrics.columns;
if (Array.isArray(columns)) {
return columns[idx];
} else if (typeof Immutable !== 'undefined') {
return columns.get(idx);
}
},
getSize: function getSize() {
var columns = this.state.columnMetrics.columns;
if (Array.isArray(columns)) {
return columns.length;
} else if (typeof Immutable !== 'undefined') {
return columns.size;
}
},
metricsUpdated: function metricsUpdated() {
var columnMetrics = this.createColumnMetrics();
this.setState({ columnMetrics: columnMetrics });
},
createColumnMetrics: function createColumnMetrics() {
var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0];
var gridColumns = this.setupGridColumns(props);
return this.getColumnMetricsType({
columns: gridColumns,
minColumnWidth: this.props.minColumnWidth,
totalWidth: props.minWidth
});
},
onColumnResize: function onColumnResize(index, width) {
var columnMetrics = ColumnMetrics.resizeColumn(this.state.columnMetrics, index, width);
this.setState({ columnMetrics: columnMetrics });
}
};
/***/ },
/* 38 */
/***/ function(module, exports) {
'use strict';
function ToObject(val) {
if (val == null) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
module.exports = Object.assign || function (target, source) {
var from;
var keys;
var to = ToObject(target);
for (var s = 1; s < arguments.length; s++) {
from = arguments[s];
keys = Object.keys(Object(from));
for (var i = 0; i < keys.length; i++) {
to[keys[i]] = from[keys[i]];
}
}
return to;
};
/***/ },
/* 39 */
/***/ function(module, exports) {
'use strict';
var RowUtils = {
get: function get(row, property) {
if (typeof row.get === 'function') {
return row.get(property);
}
return row[property];
}
};
module.exports = RowUtils;
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var Editors = {
AutoComplete: __webpack_require__(41),
DropDownEditor: __webpack_require__(43),
SimpleTextEditor: __webpack_require__(28),
CheckboxEditor: __webpack_require__(36)
};
module.exports = Editors;
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(3);
var ReactAutocomplete = __webpack_require__(42);
var ExcelColumn = __webpack_require__(15);
var optionPropType = React.PropTypes.shape({
id: React.PropTypes.required,
title: React.PropTypes.string
});
var AutoCompleteEditor = React.createClass({
displayName: 'AutoCompleteEditor',
propTypes: {
onCommit: React.PropTypes.func,
options: React.PropTypes.arrayOf(optionPropType),
label: React.PropTypes.any,
value: React.PropTypes.any,
height: React.PropTypes.number,
valueParams: React.PropTypes.arrayOf(React.PropTypes.string),
column: React.PropTypes.shape(ExcelColumn),
resultIdentifier: React.PropTypes.string,
search: React.PropTypes.string,
onKeyDown: React.PropTypes.func,
onFocus: React.PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
resultIdentifier: 'id'
};
},
handleChange: function handleChange() {
this.props.onCommit();
},
getValue: function getValue() {
var value = void 0;
var updated = {};
if (this.hasResults() && this.isFocusedOnSuggestion()) {
value = this.getLabel(this.refs.autoComplete.state.focusedValue);
if (this.props.valueParams) {
value = this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue, this.props.valueParams);
}
} else {
value = this.refs.autoComplete.state.searchTerm;
}
updated[this.props.column.key] = value;
return updated;
},
getInputNode: function getInputNode() {
return ReactDOM.findDOMNode(this).getElementsByTagName('input')[0];
},
getLabel: function getLabel(item) {
var label = this.props.label != null ? this.props.label : 'title';
if (typeof label === 'function') {
return label(item);
} else if (typeof label === 'string') {
return item[label];
}
},
hasResults: function hasResults() {
return this.refs.autoComplete.state.results.length > 0;
},
isFocusedOnSuggestion: function isFocusedOnSuggestion() {
var autoComplete = this.refs.autoComplete;
return autoComplete.state.focusedValue != null;
},
constuctValueFromParams: function constuctValueFromParams(obj, props) {
if (!props) {
return '';
}
var ret = [];
for (var i = 0, ii = props.length; i < ii; i++) {
ret.push(obj[props[i]]);
}
return ret.join('|');
},
render: function render() {
var label = this.props.label != null ? this.props.label : 'title';
return React.createElement(
'div',
{ height: this.props.height, onKeyDown: this.props.onKeyDown },
React.createElement(ReactAutocomplete, { search: this.props.search, ref: 'autoComplete', label: label, onChange: this.handleChange, onFocus: this.props.onFocus, resultIdentifier: this.props.resultIdentifier, options: this.props.options, value: { title: this.props.value } })
);
}
});
module.exports = AutoCompleteEditor;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
(function webpackUniversalModuleDefinition(root, factory) {
if(true)
module.exports = factory(__webpack_require__(2));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["ReactAutocomplete"] = factory(require("react"));
else
root["ReactAutocomplete"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__) {
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";
var React = __webpack_require__(1);
var joinClasses = __webpack_require__(2);
var Autocomplete = React.createClass({ displayName: "Autocomplete",
propTypes: {
options: React.PropTypes.any,
search: React.PropTypes.func,
resultRenderer: React.PropTypes.oneOfType([React.PropTypes.component, React.PropTypes.func]),
value: React.PropTypes.object,
onChange: React.PropTypes.func,
onError: React.PropTypes.func,
onFocus: React.PropTypes.func
},
getDefaultProps: function () {
return { search: searchArray };
},
getInitialState: function () {
var searchTerm = this.props.searchTerm ? this.props.searchTerm : this.props.value ? this.props.value.title : "";
return {
results: [],
showResults: false,
showResultsInProgress: false,
searchTerm: searchTerm,
focusedValue: null
};
},
getResultIdentifier: function (result) {
if (this.props.resultIdentifier === undefined) {
return result.id;
} else {
return result[this.props.resultIdentifier];
}
},
render: function () {
var className = joinClasses(this.props.className, "react-autocomplete-Autocomplete", this.state.showResults ? "react-autocomplete-Autocomplete--resultsShown" : undefined);
var style = {
position: "relative",
outline: "none"
};
return React.createElement("div", {
tabIndex: "1",
className: className,
onFocus: this.onFocus,
onBlur: this.onBlur,
style: style }, React.createElement("input", {
ref: "search",
className: "react-autocomplete-Autocomplete__search",
style: { width: "100%" },
onClick: this.showAllResults,
onChange: this.onQueryChange,
onFocus: this.onSearchInputFocus,
onBlur: this.onQueryBlur,
onKeyDown: this.onQueryKeyDown,
value: this.state.searchTerm }), React.createElement(Results, {
className: "react-autocomplete-Autocomplete__results",
onSelect: this.onValueChange,
onFocus: this.onValueFocus,
results: this.state.results,
focusedValue: this.state.focusedValue,
show: this.state.showResults,
renderer: this.props.resultRenderer,
label: this.props.label,
resultIdentifier: this.props.resultIdentifier }));
},
componentWillReceiveProps: function (nextProps) {
var searchTerm = nextProps.searchTerm ? nextProps.searchTerm : nextProps.value ? nextProps.value.title : "";
this.setState({ searchTerm: searchTerm });
},
componentWillMount: function () {
this.blurTimer = null;
},
/**
* Show results for a search term value.
*
* This method doesn't update search term value itself.
*
* @param {Search} searchTerm
*/
showResults: function (searchTerm) {
this.setState({ showResultsInProgress: true });
this.props.search(this.props.options, searchTerm.trim(), this.onSearchComplete);
},
showAllResults: function () {
if (!this.state.showResultsInProgress && !this.state.showResults) {
this.showResults("");
}
},
onValueChange: function (value) {
var state = {
value: value,
showResults: false
};
if (value) {
state.searchTerm = value.title;
}
this.setState(state);
if (this.props.onChange) {
this.props.onChange(value);
}
},
onSearchComplete: function (err, results) {
if (err) {
if (this.props.onError) {
this.props.onError(err);
} else {
throw err;
}
}
this.setState({
showResultsInProgress: false,
showResults: true,
results: results
});
},
onValueFocus: function (value) {
this.setState({ focusedValue: value });
},
onQueryChange: function (e) {
var searchTerm = e.target.value;
this.setState({
searchTerm: searchTerm,
focusedValue: null
});
this.showResults(searchTerm);
},
onFocus: function () {
if (this.blurTimer) {
clearTimeout(this.blurTimer);
this.blurTimer = null;
}
this.refs.search.getDOMNode().focus();
},
onSearchInputFocus: function () {
if (this.props.onFocus) {
this.props.onFocus();
}
this.showAllResults();
},
onBlur: function () {
// wrap in setTimeout so we can catch a click on results
this.blurTimer = setTimeout((function () {
if (this.isMounted()) {
this.setState({ showResults: false });
}
}).bind(this), 100);
},
onQueryKeyDown: function (e) {
if (e.key === "Enter") {
e.preventDefault();
if (this.state.focusedValue) {
this.onValueChange(this.state.focusedValue);
}
} else if (e.key === "ArrowUp" && this.state.showResults) {
e.preventDefault();
var prevIdx = Math.max(this.focusedValueIndex() - 1, 0);
this.setState({
focusedValue: this.state.results[prevIdx]
});
} else if (e.key === "ArrowDown") {
e.preventDefault();
if (this.state.showResults) {
var nextIdx = Math.min(this.focusedValueIndex() + (this.state.showResults ? 1 : 0), this.state.results.length - 1);
this.setState({
showResults: true,
focusedValue: this.state.results[nextIdx]
});
} else {
this.showAllResults();
}
}
},
focusedValueIndex: function () {
if (!this.state.focusedValue) {
return -1;
}
for (var i = 0, len = this.state.results.length; i < len; i++) {
if (this.getResultIdentifier(this.state.results[i]) === this.getResultIdentifier(this.state.focusedValue)) {
return i;
}
}
return -1;
}
});
var Results = React.createClass({ displayName: "Results",
getResultIdentifier: function (result) {
if (this.props.resultIdentifier === undefined) {
if (!result.id) {
throw "id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component";
}
return result.id;
} else {
return result[this.props.resultIdentifier];
}
},
render: function () {
var style = {
display: this.props.show ? "block" : "none",
position: "absolute",
listStyleType: "none"
};
var $__0 = this.props,
className = $__0.className,
props = (function (source, exclusion) {
var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) {
throw new TypeError();
}for (var key in source) {
if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {
rest[key] = source[key];
}
}return rest;
})($__0, { className: 1 });
return React.createElement("ul", React.__spread({}, props, { style: style, className: className + " react-autocomplete-Results" }), this.props.results.map(this.renderResult));
},
renderResult: function (result) {
var focused = this.props.focusedValue && this.getResultIdentifier(this.props.focusedValue) === this.getResultIdentifier(result);
var Renderer = this.props.renderer || Result;
return React.createElement(Renderer, {
ref: focused ? "focused" : undefined,
key: this.getResultIdentifier(result),
result: result,
focused: focused,
onMouseEnter: this.onMouseEnterResult,
onClick: this.props.onSelect,
label: this.props.label });
},
componentDidUpdate: function () {
this.scrollToFocused();
},
componentDidMount: function () {
this.scrollToFocused();
},
componentWillMount: function () {
this.ignoreFocus = false;
},
scrollToFocused: function () {
var focused = this.refs && this.refs.focused;
if (focused) {
var containerNode = this.getDOMNode();
var scroll = containerNode.scrollTop;
var height = containerNode.offsetHeight;
var node = focused.getDOMNode();
var top = node.offsetTop;
var bottom = top + node.offsetHeight;
// we update ignoreFocus to true if we change the scroll position so
// the mouseover event triggered because of that won't have an
// effect
if (top < scroll) {
this.ignoreFocus = true;
containerNode.scrollTop = top;
} else if (bottom - scroll > height) {
this.ignoreFocus = true;
containerNode.scrollTop = bottom - height;
}
}
},
onMouseEnterResult: function (e, result) {
// check if we need to prevent the next onFocus event because it was
// probably caused by a mouseover due to scroll position change
if (this.ignoreFocus) {
this.ignoreFocus = false;
} else {
// we need to make sure focused node is visible
// for some reason mouse events fire on visible nodes due to
// box-shadow
var containerNode = this.getDOMNode();
var scroll = containerNode.scrollTop;
var height = containerNode.offsetHeight;
var node = e.target;
var top = node.offsetTop;
var bottom = top + node.offsetHeight;
if (bottom > scroll && top < scroll + height) {
this.props.onFocus(result);
}
}
}
});
var Result = React.createClass({ displayName: "Result",
getDefaultProps: function () {
return {
label: function (result) {
return result.title;
}
};
},
getLabel: function (result) {
if (typeof this.props.label === "function") {
return this.props.label(result);
} else if (typeof this.props.label === "string") {
return result[this.props.label];
}
},
render: function () {
var className = joinClasses({
"react-autocomplete-Result": true,
"react-autocomplete-Result--active": this.props.focused
});
return React.createElement("li", {
style: { listStyleType: "none" },
className: className,
onClick: this.onClick,
onMouseEnter: this.onMouseEnter }, React.createElement("a", null, this.getLabel(this.props.result)));
},
onClick: function () {
this.props.onClick(this.props.result);
},
onMouseEnter: function (e) {
if (this.props.onMouseEnter) {
this.props.onMouseEnter(e, this.props.result);
}
},
shouldComponentUpdate: function (nextProps) {
return nextProps.result.id !== this.props.result.id || nextProps.focused !== this.props.focused;
}
});
/**
* Search options using specified search term treating options as an array
* of candidates.
*
* @param {Array.<Object>} options
* @param {String} searchTerm
* @param {Callback} cb
*/
function searchArray(options, searchTerm, cb) {
if (!options) {
return cb(null, []);
}
searchTerm = new RegExp(searchTerm, "i");
var results = [];
for (var i = 0, len = options.length; i < len; i++) {
if (searchTerm.exec(options[i].title)) {
results.push(options[i]);
}
}
cb(null, results);
}
module.exports = Autocomplete;
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
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 (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
/***/ }
/******/ ])
});
;
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _reactDom = __webpack_require__(3);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = __webpack_require__(2);
var EditorBase = __webpack_require__(29);
var DropDownEditor = function (_EditorBase) {
_inherits(DropDownEditor, _EditorBase);
function DropDownEditor() {
_classCallCheck(this, DropDownEditor);
return _possibleConstructorReturn(this, Object.getPrototypeOf(DropDownEditor).apply(this, arguments));
}
_createClass(DropDownEditor, [{
key: 'getInputNode',
value: function getInputNode() {
return _reactDom2['default'].findDOMNode(this);
}
}, {
key: 'onClick',
value: function onClick() {
this.getInputNode().focus();
}
}, {
key: 'onDoubleClick',
value: function onDoubleClick() {
this.getInputNode().focus();
}
}, {
key: 'render',
value: function render() {
return React.createElement(
'select',
{ style: this.getStyle(), defaultValue: this.props.value, onBlur: this.props.onBlur, onChange: this.onChange },
this.renderOptions()
);
}
}, {
key: 'renderOptions',
value: function renderOptions() {
var options = [];
this.props.options.forEach(function (name) {
if (typeof name === 'string') {
options.push(React.createElement(
'option',
{ key: name, value: name },
name
));
} else {
options.push(React.createElement(
'option',
{ key: name.id, value: name.value, title: name.title },
name.value
));
}
}, this);
return options;
}
}]);
return DropDownEditor;
}(EditorBase);
DropDownEditor.propTypes = {
options: React.PropTypes.arrayOf(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.objectOf({ id: React.PropTypes.string, title: React.PropTypes.string, meta: React.PropTypes.string })])).isRequired
};
module.exports = DropDownEditor;
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// not including this
// it currently requires the whole of moment, which we dont want to take as a dependency
var ImageFormatter = __webpack_require__(45);
var Formatters = {
ImageFormatter: ImageFormatter
};
module.exports = Formatters;
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var PendingPool = {};
var ReadyPool = {};
var ImageFormatter = React.createClass({
displayName: 'ImageFormatter',
propTypes: {
value: React.PropTypes.string.isRequired
},
getInitialState: function getInitialState() {
return {
ready: false
};
},
componentWillMount: function componentWillMount() {
this._load(this.props.value);
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.props.value) {
this.setState({ value: null });
this._load(nextProps.value);
}
},
_load: function _load(src) {
var imageSrc = src;
if (ReadyPool[imageSrc]) {
this.setState({ value: imageSrc });
return;
}
if (PendingPool[imageSrc]) {
PendingPool[imageSrc].push(this._onLoad);
return;
}
PendingPool[imageSrc] = [this._onLoad];
var img = new Image();
img.onload = function () {
PendingPool[imageSrc].forEach(function (callback) {
callback(imageSrc);
});
delete PendingPool[imageSrc];
img.onload = null;
imageSrc = undefined;
};
img.src = imageSrc;
},
_onLoad: function _onLoad(src) {
if (this.isMounted() && src === this.props.value) {
this.setState({
value: src
});
}
},
render: function render() {
var style = this.state.value ? { backgroundImage: 'url(' + this.state.value + ')' } : undefined;
return React.createElement('div', { className: 'react-grid-image', style: style });
}
});
module.exports = ImageFormatter;
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var React = __webpack_require__(2);
var Toolbar = React.createClass({
displayName: "Toolbar",
propTypes: {
onAddRow: React.PropTypes.func,
onToggleFilter: React.PropTypes.func,
enableFilter: React.PropTypes.bool,
numberOfRows: React.PropTypes.number
},
onAddRow: function onAddRow() {
if (this.props.onAddRow !== null && this.props.onAddRow instanceof Function) {
this.props.onAddRow({ newRowIndex: this.props.numberOfRows });
}
},
getDefaultProps: function getDefaultProps() {
return {
enableAddRow: true
};
},
renderAddRowButton: function renderAddRowButton() {
if (this.props.onAddRow) {
return React.createElement(
"button",
{ type: "button", className: "btn", onClick: this.onAddRow },
"Add Row"
);
}
},
renderToggleFilterButton: function renderToggleFilterButton() {
if (this.props.enableFilter) {
return React.createElement(
"button",
{ type: "button", className: "btn", onClick: this.props.onToggleFilter },
"Filter Rows"
);
}
},
render: function render() {
return React.createElement(
"div",
{ className: "react-grid-Toolbar" },
React.createElement(
"div",
{ className: "tools" },
this.renderAddRowButton(),
this.renderToggleFilterButton()
)
);
}
});
module.exports = Toolbar;
/***/ }
/******/ ])
});
; |
library/src/pivotal-ui-react/flex-grids/flex-grids.js | sjolicoeur/pivotal-ui | import React from 'react';
import PropTypes from 'prop-types';
import {mergeProps} from 'pui-react-helpers';
import classnames from 'classnames';
import 'pui-css-flex-grids';
export class Grid extends React.Component {
static propTypes = {
gutter: PropTypes.bool
};
static defaultProps = {
gutter: true
};
render() {
const {gutter, ...props} = this.props;
const newProps = mergeProps(props, {className: classnames('grid', gutter ? '' : 'grid-nogutter')});
return <div {...newProps}/>;
}
}
export const FlexCol = (props) => {
const {col, fixed, grow, alignment, contentAlignment, breakpoint, ...other} = props;
const colClassName = classnames({
[`col-${col}`]: col
});
const fixedClassName = classnames({
'col-fixed': fixed
});
const growClassName = classnames({
[`col-grow-${grow}`]: grow
});
const alignmentClassName = classnames({
[`col-align-${alignment}`]: alignment
});
const contentAlignmentClassName = classnames({
[`col-${contentAlignment}`]: contentAlignment
});
const breakpointClassName = classnames({
[`col-${breakpoint}`]: breakpoint
});
const className = classnames('col', colClassName, fixedClassName, growClassName, alignmentClassName,
contentAlignmentClassName, breakpointClassName);
const newProps = mergeProps(other, {className});
return <div {...newProps}/>;
};
FlexCol.propTypes = {
col: PropTypes.number,
fixed: PropTypes.bool,
grow: PropTypes.number,
alignment: PropTypes.oneOf(['top', 'middle', 'bottom']),
contentAlignment: PropTypes.oneOf(['top', 'middle', 'bottom']),
breakpoint: PropTypes.oneOf(['sm', 'md', 'lg'])
}; |
docs/app/Examples/views/Item/Variations/index.js | koenvg/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const Variations = () => (
<ExampleSection title='Variations'>
<ComponentExample
title='Divided'
description='Items can be divided to better distinguish between grouped content.'
examplePath='views/Item/Variations/ItemExampleDivided'
/>
<ComponentExample
title='Relaxed'
description='A group of items can relax its padding to provide more negative space.'
examplePath='views/Item/Variations/ItemExampleRelaxed'
/>
<ComponentExample examplePath='views/Item/Variations/ItemExampleVeryRelaxed' />
<ComponentExample
title='Link Item'
description='An item can be formatted so that the entire contents link to another page.'
examplePath='views/Item/Variations/ItemExampleLink'
/>
<ComponentExample
title='Vertical Alignment'
description='Content can specify its vertical alignment.'
examplePath='views/Item/Variations/ItemExampleAlignment'
/>
<ComponentExample
title='Floated Content'
description='Any content element can be floated left or right.'
examplePath='views/Item/Variations/ItemExampleFloated'
/>
</ExampleSection>
)
export default Variations
|
app/javascript/mastodon/features/direct_timeline/components/conversations_list.js | sylph-sin-tyaku/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ConversationContainer from '../containers/conversation_container';
import ScrollableList from '../../../components/scrollable_list';
import { debounce } from 'lodash';
export default class ConversationsList extends ImmutablePureComponent {
static propTypes = {
conversations: ImmutablePropTypes.list.isRequired,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
onLoadMore: PropTypes.func,
shouldUpdateScroll: PropTypes.func,
};
getCurrentIndex = id => this.props.conversations.findIndex(x => x.get('id') === id)
handleMoveUp = id => {
const elementIndex = this.getCurrentIndex(id) - 1;
this._selectChild(elementIndex, true);
}
handleMoveDown = id => {
const elementIndex = this.getCurrentIndex(id) + 1;
this._selectChild(elementIndex, false);
}
_selectChild (index, align_top) {
const container = this.node.node;
const element = container.querySelector(`article:nth-of-type(${index + 1}) .focusable`);
if (element) {
if (align_top && container.scrollTop > element.offsetTop) {
element.scrollIntoView(true);
} else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) {
element.scrollIntoView(false);
}
element.focus();
}
}
setRef = c => {
this.node = c;
}
handleLoadOlder = debounce(() => {
const last = this.props.conversations.last();
if (last && last.get('last_status')) {
this.props.onLoadMore(last.get('last_status'));
}
}, 300, { leading: true })
render () {
const { conversations, onLoadMore, ...other } = this.props;
return (
<ScrollableList {...other} onLoadMore={onLoadMore && this.handleLoadOlder} scrollKey='direct' ref={this.setRef}>
{conversations.map(item => (
<ConversationContainer
key={item.get('id')}
conversationId={item.get('id')}
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
/>
))}
</ScrollableList>
);
}
}
|
src/app/core/atoms/icon/icons/mail.js | blowsys/reservo | import React from 'react'; const Mail = (props) => <svg {...props} viewBox="0 0 48 48"><g><path d="M0,2.4000015L7.5999756,9.7999944 16,17.999999 24.399963,9.7999944 31.899963,2.4000015 32,2.4000015 32,23.400001 0,23.400001z M1.8999634,0L16,0 30.099976,0 23,7.099998 16,14.099997 9,7.099998z" transform="rotate(0,24,24) translate(0,6.44999885559082) scale(1.5,1.5)"/></g></svg>; export default Mail;
|
examples/resources/scripts/server.js | allantatter/laravel-react | 'use strict';
console.log('Initalizing server.');
var express = require('express');
var React = require('react');
var Router = require('react-router');
// Transparently support JSX
require('node-jsx').install({harmony: true});
require('dotenv').load({path: '../../.env'});
var app = express();
var componentsDir = process.REACT_COMPONENTS_DIR || 'components';
var extension = process.REACT_EXTENSION || 'jsx';
var port = process.REACT_SERVER_URL || 3000;
app.get('/', function(req, res) {
var type = req.query.type;
var props = JSON.parse(req.query.props || '{}');
if (type === 'react-router') {
var routes = require('./' + req.query.routes + '.' + extension);
Router.run(routes, req.query.path, function (Handler) {
var html = React.renderToString(React.createElement(Handler, props));
res.send(html);
});
} else {
var component = require('./' + componentsDir + '/' + req.query.component + '.' + extension);
var html = React.renderToString(React.createElement(component, props));
res.send(html);
}
});
app.listen(port);
console.log('Server listening on port ' + port + '...');
|
src/js/components/acl/modals/add_principals_modal.js | rafaelfbs/realizejs | import React, { Component } from 'react';
import PropTypes from '../../../prop_types';
import $ from 'jquery';
import { autobind, mixin } from '../../../utils/decorators';
import {
Modal,
ModalHeader,
ModalContent,
ModalFooter,
CloseModalButton,
Button,
Grid,
} from '../../../components';
import { RequestHandlerMixin } from '../../../mixins';
@mixin(RequestHandlerMixin)
export default class AddPrincipalsModal extends Component {
static propTypes = {
resource: PropTypes.object,
resourceType: PropTypes.string,
className: PropTypes.string,
modalId: PropTypes.string,
potentialPrincipalsBaseUrl: PropTypes.string,
principalsTypeBaseUrl: PropTypes.string,
};
static defaultProps = {
className: 'add-principals-modal',
modalId: 'add-principals-modal',
potentialPrincipalsBaseUrl: '/wkm_acl_ui/principals/potential_principals',
principalsTypeBaseUrl: '/wkm_acl_ui/principals/types',
gridProps: {
selectable: true,
paginationOnTop: false,
paginationConfigs: {
perPage: 10,
window: 4,
param: 'p',
},
columns: {
name: {
label: 'Nome',
},
principal_type_translated: {
label: 'Tipo',
},
},
tableClassName: 'table bordered',
actionButtons: {
member: [],
collection: [],
},
},
};
state = {
selectedPrincipal: null,
potentialPrincipals: [],
principalType: null,
};
componentWillMount() {
$.ajax({
url: this.props.principalsTypeBaseUrl,
method: 'GET',
dataType: 'json',
success: (data) => {
this.setState({
principalType: data[0].name,
});
},
});
}
componentWillReceiveProps() {
this.refs.grid.backToInitialState();
}
getData() {
return {
dataRows: this.state.potentialPrincipals,
count: this.state.potentialPrincipals.length,
};
}
getSelectedDatas() {
const selectedRowsIds = this.refs.grid.state.selectedRowIds;
const dataRows = this.refs.grid.state.dataRows;
const selectedDatas = [];
selectedRowsIds.forEach((rowId) => {
dataRows.forEach((data) => {
if (data.id === rowId) {
selectedDatas.push({
principal_id: data.id,
principal_type: data.principal_type,
});
}
});
});
return selectedDatas;
}
addPrincipal(selectedDatas) {
this.props.handleAddPrincipal(selectedDatas);
}
filters() {
return {
resource: 'q',
inputs: {
name_cont: {
label: 'Nome',
className: 'col s12 l6 m6',
},
principal_type: {
label: 'Tipo',
component: 'autocomplete',
optionsUrl: this.props.principalsTypeBaseUrl,
searchParam: 'principal_type',
className: 'col s12 l6 m6',
scope: 'global',
},
resource_id: {
value: this.props.resource.id,
component: 'hidden',
scope: 'global',
},
resource_type: {
value: this.props.resourceType,
component: 'hidden',
scope: 'global',
},
per_page: {
value: 10,
component: 'hidden',
scope: 'global',
},
},
};
}
@autobind
handleSelectPrincipal(event, data) {
this.setState({
selectedPrincipal: data,
});
}
@autobind
handleAddPrincipal() {
const selectedDatas = this.getSelectedDatas();
if (selectedDatas.length === 0) {
alert('Necessário selecionar alguém para adicionar');
} else {
this.addPrincipal(selectedDatas);
}
}
render() {
return (
<Modal
id={this.props.modalId}
style={{ 'z-index': '9000' }}
className={this.props.className}
headerSize={this.props.headerSize}
ref="add-principals-modal"
>
<ModalHeader>
<h5>Selecionar Usuário/Grupo</h5>
</ModalHeader>
<ModalContent>
<div className="principal-modal-content">
<Grid
ref="grid"
{...this.props.gridProps}
url={this.props.potentialPrincipalsBaseUrl}
filter={this.filters()}
eagerLoad
onClickRow={this.handleSelectPrincipal}
/>
</div>
</ModalContent>
<ModalFooter>
<div className="modal-footer" style={{ float: 'right' }}>
<CloseModalButton modalId={this.props.modalId} />
<Button
name="Adicionar"
element="a"
onClick={this.handleAddPrincipal}
/>
</div>
</ModalFooter>
</Modal>
);
}
}
|
src/components/Button/Button.js | akikoo/react-ui-style-guide | require('./Button.scss');
import React from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
class Button extends React.Component {
constructor(props) {
super(props);
}
render() {
let classes = classNames(
'button',
this.props.modifiers
);
return (
<button className={classes} type={this.props.type}>
{this.props.text}
</button>
);
}
}
Button.propTypes = {
type: React.PropTypes.string,
text: React.PropTypes.string.isRequired,
modifiers: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.array])
};
Button.defaultProps = {
type: 'submit',
text: '',
modifiers: [
'button--primary',
'button--medium'
]
};
export default Button;
|
src/client/controllers/editor/achievement.js | bookbrainz/bookbrainz-site | /*
* Copyright (C) 2016 Daniel Hsing
* 2015 Ben Ockmore
* 2015 Sean Burke
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 General Public License for more details.
*
* You should have received a copy of the GNU 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 {
extractEditorProps,
extractLayoutProps
} from '../../helpers/props';
import AchievementsTab from '../../components/pages/parts/editor-achievements';
import {AppContainer} from 'react-hot-loader';
import EditorContainer from '../../containers/editor';
import Layout from '../../containers/layout';
import React from 'react';
import ReactDOM from 'react-dom';
const propsTarget = document.getElementById('props');
const props = propsTarget ? JSON.parse(propsTarget.innerHTML) : {};
ReactDOM.hydrate(
<AppContainer>
<Layout {...extractLayoutProps(props)}>
<EditorContainer
{...extractEditorProps(props)}
>
<AchievementsTab
achievement={props.achievement}
editor={props.editor}
isOwner={props.isOwner}
/>
</EditorContainer>
</Layout>
</AppContainer>,
document.getElementById('target')
);
/*
* As we are not exporting a component,
* we cannot use the react-hot-loader module wrapper,
* but instead directly use webpack Hot Module Replacement API
*/
if (module.hot) {
module.hot.accept();
}
|
src/docs/examples/TextInput/ExampleOptional.js | bfletcherbiggs/DocreactJS | import React from 'react';
import TextInput from 'component-library/TextInput';
/** Optional TextBox */
class ExampleOptional extends React.Component {
render() {
return (
<TextInput
htmlId="example-optional"
label="First Name"
name="firstname"
onChange={() => {}}
/>
)
}
}
export default ExampleOptional;
|
node_modules/gulp-babel/node_modules/babel-core/lib/transformation/transformers/optimisation/react.inline-elements.js | drankadank/server | "use strict";
exports.__esModule = true;
// istanbul ignore next
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
var _helpersReact = require("../../helpers/react");
var react = _interopRequireWildcard(_helpersReact);
var _types = require("../../../types");
var t = _interopRequireWildcard(_types);
var metadata = {
optional: true
};
exports.metadata = metadata;
/**
* [Please add a description.]
*/
function hasRefOrSpread(attrs) {
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
if (t.isJSXSpreadAttribute(attr)) return true;
if (isJSXAttributeOfName(attr, "ref")) return true;
}
return false;
}
/**
* [Please add a description.]
*/
function isJSXAttributeOfName(attr, name) {
return t.isJSXAttribute(attr) && t.isJSXIdentifier(attr.name, { name: name });
}
/**
* [Please add a description.]
*/
var visitor = {
/**
* [Please add a description.]
*/
JSXElement: function JSXElement(node, parent, scope, file) {
// filter
var open = node.openingElement;
if (hasRefOrSpread(open.attributes)) return;
// init
var isComponent = true;
var props = t.objectExpression([]);
var obj = t.objectExpression([]);
var key = t.literal(null);
var type = open.name;
if (t.isJSXIdentifier(type) && react.isCompatTag(type.name)) {
type = t.literal(type.name);
isComponent = false;
}
function pushElemProp(key, value) {
pushProp(obj.properties, t.identifier(key), value);
}
function pushProp(objProps, key, value) {
objProps.push(t.property("init", key, value));
}
if (node.children.length) {
var children = react.buildChildren(node);
children = children.length === 1 ? children[0] : t.arrayExpression(children);
pushProp(props.properties, t.identifier("children"), children);
}
// props
for (var i = 0; i < open.attributes.length; i++) {
var attr = open.attributes[i];
if (isJSXAttributeOfName(attr, "key")) {
key = attr.value;
} else {
pushProp(props.properties, attr.name, attr.value || t.identifier("true"));
}
}
if (isComponent) {
props = t.callExpression(file.addHelper("default-props"), [t.memberExpression(type, t.identifier("defaultProps")), props]);
}
// metadata
pushElemProp("$$typeof", file.addHelper("typeof-react-element"));
pushElemProp("type", type);
pushElemProp("key", key);
pushElemProp("ref", t.literal(null));
pushElemProp("props", props);
pushElemProp("_owner", t.literal(null));
return obj;
}
};
exports.visitor = visitor; |
src/names/selected/SelectedName.js | VasilyShelkov/ClientRelationshipManagerUI | import React from 'react';
import { Switch, Route } from 'react-router';
import Drawer from 'material-ui/Drawer';
import { Toolbar, ToolbarGroup } from 'material-ui/Toolbar';
import IconButton from 'material-ui/IconButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import { List } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import SelectedUnprotectedActionsWithData from './toolbarActions/unprotected/SelectedUnprotectedActionsWithData';
import SelectedProtectedActionsWithData from './toolbarActions/protected/SelectedProtectedActionsWithData';
import SelectedClientActionsWithData from './toolbarActions/client/SelectedClientActionsWithData';
import RemoveUnprotectedNameButton from './toolbarActions/unprotected/RemoveUnprotectedNameButton';
import RemoveProtectedNameButton from './toolbarActions/protected/RemoveProtectedNameButton';
import RemoveClientButton from './toolbarActions/client/RemoveClientButton';
import NameDetails from './NameDetails';
import CompanyDetails from './CompanyDetails';
import Comments from './comments/CommentsWithData';
import LoadingSpinner from '../../shared/LoadingSpinner';
export default ({
name,
match: {
params: { nameListType },
},
closeNameDetails,
}) => (
<Drawer
containerStyle={{ zIndex: '1100' }}
width={250}
openSecondary
open={Boolean(name)}
>
{name ? (
<div id="selectedName">
<Toolbar>
<ToolbarGroup firstChild>
<IconButton onClick={() => closeNameDetails(nameListType)}>
<NavigationClose />
</IconButton>
</ToolbarGroup>
<Switch>
<Route
path="/account/names/unprotected"
render={() => <SelectedUnprotectedActionsWithData name={name} />}
/>
<Route
path="/account/names/(protected|metWithProtected)"
render={() => <SelectedProtectedActionsWithData name={name} />}
/>
<Route
path="/account/names/clients"
render={() => <SelectedClientActionsWithData name={name} />}
/>
</Switch>
<ToolbarGroup lastChild>
<Switch>
<Route
path={`/account/names/unprotected`}
render={() => <RemoveUnprotectedNameButton name={name} />}
/>
<Route
path={`/account/names/(protected|metWithProtected)`}
render={() => <RemoveProtectedNameButton name={name} />}
/>
<Route
path={`/account/names/clients`}
render={() => <RemoveClientButton name={name} />}
/>
</Switch>
</ToolbarGroup>
</Toolbar>
<List>
<NameDetails
isProtected={
nameListType === 'protected' ||
nameListType === 'metWithProtected' ||
nameListType === 'client'
}
name={{
id: name.id,
firstName: name.firstName,
lastName: name.lastName,
phone: name.phone,
}}
/>
<Divider />
<CompanyDetails company={name.company} />
<Divider />
<Comments
id={name.id}
firstName={name.firstName}
lastName={name.lastName}
/>
</List>
</div>
) : (
<LoadingSpinner />
)}
</Drawer>
);
|
docs/yuidoc-p5-theme/assets/js/reference.js | polyrhythmatic/p5.js-sound | (function () {// Underscore.js 1.5.2
// http://underscorejs.org
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.5.2';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, length = obj.length; i < length; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var length = obj.length;
if (length !== +length) {
var keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
index = keys ? keys[--length] : --length;
if (!initial) {
memo = obj[index];
initial = true;
} else {
memo = iterator.call(context, memo, obj[index], index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
return _.filter(obj, function(value, index, list) {
return !iterator.call(context, value, index, list);
}, context);
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) {
return value === target;
});
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs, first) {
if (_.isEmpty(attrs)) return first ? void 0 : [];
return _[first ? 'find' : 'filter'](obj, function(value) {
for (var key in attrs) {
if (attrs[key] !== value[key]) return false;
}
return true;
});
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.where(obj, attrs, true);
};
// Return the maximum element or (element-based computation).
// Can't optimize arrays of integers longer than 65,535 elements.
// See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797)
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.max.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity, value: -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed > result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.min.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity, value: Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Shuffle an array, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var rand;
var index = 0;
var shuffled = [];
each(obj, function(value) {
rand = _.random(index++);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
// Sample **n** random values from an array.
// If **n** is not specified, returns a single random element from the array.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (arguments.length < 2 || guard) {
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
return _.isFunction(value) ? value : function(obj){ return obj[value]; };
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, value, context) {
var iterator = lookupIterator(value);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, value, context) {
var result = {};
var iterator = value == null ? _.identity : lookupIterator(value);
each(obj, function(value, index) {
var key = iterator.call(context, value, index, obj);
behavior(result, key, value);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, key, value) {
(_.has(result, key) ? result[key] : (result[key] = [])).push(value);
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, key, value) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, key) {
_.has(result, key) ? result[key]++ : result[key] = 1;
});
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator, context) {
iterator = iterator == null ? _.identity : lookupIterator(iterator);
var value = iterator.call(context, obj);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
}
return low;
};
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
return (n == null) || guard ? array[0] : slice.call(array, 0, n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if ((n == null) || guard) {
return array[array.length - 1];
} else {
return slice.call(array, Math.max(array.length - n, 0));
}
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, (n == null) || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, output) {
if (shallow && _.every(input, _.isArray)) {
return concat.apply(output, input);
}
each(input, function(value) {
if (_.isArray(value) || _.isArguments(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
} else {
output.push(value);
}
});
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator, context) {
if (_.isFunction(isSorted)) {
context = iterator;
iterator = isSorted;
isSorted = false;
}
var initial = iterator ? _.map(array, iterator, context) : array;
var results = [];
var seen = [];
each(initial, function(value, index) {
if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
seen.push(value);
results.push(array[index]);
}
});
return results;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.contains(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var length = _.max(_.pluck(arguments, "length").concat(0));
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(arguments, '' + i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, length = list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, length = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var hasIndex = from != null;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
}
var i = (hasIndex ? from : array.length);
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(length);
while(idx < length) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
var args, bound;
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context.
_.partial = function(func) {
var args = slice.call(arguments, 1);
return function() {
return func.apply(this, args.concat(slice.call(arguments)));
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length === 0) throw new Error("bindAll must be passed function names");
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function() {
previous = options.leading === false ? 0 : new Date;
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date;
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
return function() {
context = this;
args = arguments;
timestamp = new Date();
var later = function() {
var last = (new Date()) - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) result = func.apply(context, args);
return result;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func];
push.apply(args, arguments);
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = new Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = new Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
each(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
for (var key in obj) {
if (!_.contains(keys, key)) copy[key] = obj[key];
}
return copy;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
if (obj[prop] === void 0) obj[prop] = source[prop];
}
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] == a) return bStack[length] == b;
}
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
_.isFunction(bCtor) && (bCtor instanceof bCtor))) {
return false;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Optimize `isFunction` if appropriate.
if (typeof (/./) !== 'function') {
_.isFunction = function(obj) {
return typeof obj === 'function';
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function(n, iterator, context) {
var accum = Array(Math.max(0, n));
for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// List of HTML entities for escaping.
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
};
entityMap.unescape = _.invert(entityMap.escape);
// Regexes containing the keys and values listed immediately above.
var entityRegexes = {
escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
};
// Functions for escaping and unescaping strings to/from HTML interpolation.
_.each(['escape', 'unescape'], function(method) {
_[method] = function(string) {
if (string == null) return '';
return ('' + string).replace(entityRegexes[method], function(match) {
return entityMap[method][match];
});
};
});
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property) {
if (object == null) return void 0;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
_.extend(_.prototype, {
// Start chaining a wrapped Underscore object.
chain: function() {
this._chain = true;
return this;
},
// Extracts the result from a wrapped and chained object.
value: function() {
return this._wrapped;
}
});
// AMD define happens at the end for compatibility with AMD loaders
// that don't enforce next-turn semantics on modules.
if (typeof define === 'function' && define.amd) {
define('underscore', [],function() {
return _;
});
}
}).call(this);
// Backbone.js 1.1.0
// (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc.
// (c) 2011-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://backbonejs.org
(function(root, factory) {
// Set up Backbone appropriately for the environment.
if (typeof exports !== 'undefined') {
// Node/CommonJS, no need for jQuery in that case.
factory(root, exports, require('underscore'));
} else if (typeof define === 'function' && define.amd) {
// AMD
define('backbone',['underscore', 'exports'], function(_, exports) { // EDITED: removed 'jquery' module call
// Export global even in AMD case in case this script is loaded with
// others that may still expect a global Backbone.
root.Backbone = factory(root, exports, _, jQuery); // jQuery must be global
});
} else {
// Browser globals
root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
}
}(this, function(root, Backbone, _, $) {
// Initial Setup
// -------------
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
var previousBackbone = root.Backbone;
// Create local references to array methods we'll want to use later.
var array = [];
var push = array.push;
var slice = array.slice;
var splice = array.splice;
// Current version of the library. Keep in sync with `package.json`.
Backbone.VERSION = '1.1.0';
// For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable.
Backbone.$ = $;
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
// will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
// set a `X-Http-Method-Override` header.
Backbone.emulateHTTP = false;
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
// `application/json` requests ... will encode the body as
// `application/x-www-form-urlencoded` instead and will send the model in a
// form param named `model`.
Backbone.emulateJSON = false;
// Backbone.Events
// ---------------
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may bind with `on` or remove with `off` callback
// functions to an event; `trigger`-ing an event fires all callbacks in
// succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
var Events = Backbone.Events = {
// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
},
// Bind an event to only be triggered a single time. After the first time
// the callback is invoked, it will be removed.
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
// Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
off: function(name, callback, context) {
var retain, ev, events, names, i, l, j, k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
if (!name && !callback && !context) {
this._events = {};
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (events = this._events[name]) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
(context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length) delete this._events[name];
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},
// Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo) return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object') callback = this;
if (obj) (listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
}
return this;
}
};
// Regular expression used to split event strings.
var eventSplitter = /\s+/;
// Implement fancy features of the Events API such as multiple event
// names `"change blur"` and jQuery-style event maps `{change: action}`
// in terms of the existing API.
var eventsApi = function(obj, action, name, rest) {
if (!name) return true;
// Handle event maps.
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
// Handle space separated event names.
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).
var triggerEvents = function(events, args) {
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
}
};
var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
// Inversion-of-control versions of `on` and `once`. Tell *this* object to
// listen to an event in another object ... keeping track of what it's
// listening to.
_.each(listenMethods, function(implementation, method) {
Events[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object') callback = this;
obj[implementation](name, callback, this);
return this;
};
});
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
// Allow the `Backbone` object to serve as a global event bus, for folks who
// want global "pubsub" in a convenient place.
_.extend(Backbone, Events);
// Backbone.Model
// --------------
// Backbone **Models** are the basic data object in the framework --
// frequently representing a row in a table in a database on your server.
// A discrete chunk of data and a bunch of useful, related methods for
// performing computations and transformations on that data.
// Create a new model with the specified attributes. A client id (`cid`)
// is automatically generated and assigned for you.
var Model = Backbone.Model = function(attributes, options) {
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// A hash of attributes whose current and previous value differ.
changed: null,
// The value returned during the last failed validation.
validationError: null,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute: 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Return a copy of the model's `attributes` object.
toJSON: function(options) {
return _.clone(this.attributes);
},
// Proxy `Backbone.sync` by default -- but override this if you need
// custom syncing semantics for *this* particular model.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Get the value of an attribute.
get: function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape: function(attr) {
return _.escape(this.get(attr));
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has: function(attr) {
return this.get(attr) != null;
},
// Set a hash of model attributes on the object, firing `"change"`. This is
// the core primitive operation of a model, updating the data and notifying
// anyone who needs to know about the change in state. The heart of the beast.
set: function(key, val, options) {
var attr, attrs, unset, changes, silent, changing, prev, current;
if (key == null) return this;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
// Run validation.
if (!this._validate(attrs, options)) return false;
// Extract attributes and options.
unset = options.unset;
silent = options.silent;
changes = [];
changing = this._changing;
this._changing = true;
if (!changing) {
this._previousAttributes = _.clone(this.attributes);
this.changed = {};
}
current = this.attributes, prev = this._previousAttributes;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// For each `set` attribute, update or delete the current value.
for (attr in attrs) {
val = attrs[attr];
if (!_.isEqual(current[attr], val)) changes.push(attr);
if (!_.isEqual(prev[attr], val)) {
this.changed[attr] = val;
} else {
delete this.changed[attr];
}
unset ? delete current[attr] : current[attr] = val;
}
// Trigger all relevant attribute changes.
if (!silent) {
if (changes.length) this._pending = true;
for (var i = 0, l = changes.length; i < l; i++) {
this.trigger('change:' + changes[i], this, current[changes[i]], options);
}
}
// You might be wondering why there's a `while` loop here. Changes can
// be recursively nested within `"change"` events.
if (changing) return this;
if (!silent) {
while (this._pending) {
this._pending = false;
this.trigger('change', this, options);
}
}
this._pending = false;
this._changing = false;
return this;
},
// Remove an attribute from the model, firing `"change"`. `unset` is a noop
// if the attribute doesn't exist.
unset: function(attr, options) {
return this.set(attr, void 0, _.extend({}, options, {unset: true}));
},
// Clear all attributes on the model, firing `"change"`.
clear: function(options) {
var attrs = {};
for (var key in this.attributes) attrs[key] = void 0;
return this.set(attrs, _.extend({}, options, {unset: true}));
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged: function(attr) {
if (attr == null) return !_.isEmpty(this.changed);
return _.has(this.changed, attr);
},
// Return an object containing all the attributes that have changed, or
// false if there are no changed attributes. Useful for determining what
// parts of a view need to be updated and/or what attributes need to be
// persisted to the server. Unset attributes will be set to undefined.
// You can also pass an attributes object to diff against the model,
// determining if there *would be* a change.
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
var val, changed = false;
var old = this._changing ? this._previousAttributes : this.attributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function(attr) {
if (attr == null || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function() {
return _.clone(this._previousAttributes);
},
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overridden,
// triggering a `"change"` event.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
if (!model.set(model.parse(resp, options), options)) return false;
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function(key, val, options) {
var attrs, method, xhr, attributes = this.attributes;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options = _.extend({validate: true}, options);
// If we're not waiting and attributes exist, save acts as
// `set(attr).save(null, opts)` with validation. Otherwise, check if
// the model will be valid when the attributes, if any, are set.
if (attrs && !options.wait) {
if (!this.set(attrs, options)) return false;
} else {
if (!this._validate(attrs, options)) return false;
}
// Set temporary attributes if `{wait: true}`.
if (attrs && options.wait) {
this.attributes = _.extend({}, attributes, attrs);
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
// Ensure attributes are restored during synchronous saves.
model.attributes = attributes;
var serverAttrs = model.parse(resp, options);
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
return false;
}
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
if (method === 'patch') options.attrs = attrs;
xhr = this.sync(method, this, options);
// Restore attributes.
if (attrs && options.wait) this.attributes = attributes;
return xhr;
},
// Destroy this model on the server if it was already persisted.
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
var destroy = function() {
model.trigger('destroy', model, model.collection, options);
};
options.success = function(resp) {
if (options.wait || model.isNew()) destroy();
if (success) success(model, resp, options);
if (!model.isNew()) model.trigger('sync', model, resp, options);
};
if (this.isNew()) {
options.success();
return false;
}
wrapError(this, options);
var xhr = this.sync('delete', this, options);
if (!options.wait) destroy();
return xhr;
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url: function() {
var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse: function(resp, options) {
return resp;
},
// Create a new model with identical attributes to this one.
clone: function() {
return new this.constructor(this.attributes);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function() {
return this.id == null;
},
// Check if the model is currently in a valid state.
isValid: function(options) {
return this._validate({}, _.extend(options || {}, { validate: true }));
},
// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
_validate: function(attrs, options) {
if (!options.validate || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validationError = this.validate(attrs, options) || null;
if (!error) return true;
this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
return false;
}
});
// Underscore methods that we want to implement on the Model.
var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
// Mix in each Underscore method as a proxy to `Model#attributes`.
_.each(modelMethods, function(method) {
Model.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.attributes);
return _[method].apply(_, args);
};
});
// Backbone.Collection
// -------------------
// If models tend to represent a single row of data, a Backbone Collection is
// more analagous to a table full of data ... or a small slice or page of that
// table, or a collection of rows that belong together for a particular reason
// -- all of the messages in this particular folder, all of the documents
// belonging to this particular author, and so on. Collections maintain
// indexes of their models, both in order, and for lookup by `id`.
// Create a new **Collection**, perhaps to contain a specific type of `model`.
// If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
var Collection = Backbone.Collection = function(models, options) {
options || (options = {});
if (options.model) this.model = options.model;
if (options.comparator !== void 0) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, _.extend({silent: true}, options));
};
// Default options for `Collection#set`.
var setOptions = {add: true, remove: true, merge: true};
var addOptions = {add: true, remove: false};
// Define the Collection's inheritable methods.
_.extend(Collection.prototype, Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: Model,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON: function(options) {
return this.map(function(model){ return model.toJSON(options); });
},
// Proxy `Backbone.sync` by default.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Add a model, or list of models to the set.
add: function(models, options) {
return this.set(models, _.extend({merge: false}, options, addOptions));
},
// Remove a model, or a list of models from the set.
remove: function(models, options) {
var singular = !_.isArray(models);
models = singular ? [models] : _.clone(models);
options || (options = {});
var i, l, index, model;
for (i = 0, l = models.length; i < l; i++) {
model = models[i] = this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byId[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model);
}
return singular ? models[0] : models;
},
// Update a collection by `set`-ing a new list of models, adding new ones,
// removing models that are no longer present, and merging models that
// already exist in the collection, as necessary. Similar to **Model#set**,
// the core operation for updating the data contained by the collection.
set: function(models, options) {
options = _.defaults({}, options, setOptions);
if (options.parse) models = this.parse(models, options);
var singular = !_.isArray(models);
models = singular ? (models ? [models] : []) : _.clone(models);
var i, l, id, model, attrs, existing, sort;
var at = options.at;
var targetModel = this.model;
var sortable = this.comparator && (at == null) && options.sort !== false;
var sortAttr = _.isString(this.comparator) ? this.comparator : null;
var toAdd = [], toRemove = [], modelMap = {};
var add = options.add, merge = options.merge, remove = options.remove;
var order = !sortable && add && remove ? [] : false;
// Turn bare objects into model references, and prevent invalid models
// from being added.
for (i = 0, l = models.length; i < l; i++) {
attrs = models[i];
if (attrs instanceof Model) {
id = model = attrs;
} else {
id = attrs[targetModel.prototype.idAttribute];
}
// If a duplicate is found, prevent it from being added and
// optionally merge it into the existing model.
if (existing = this.get(id)) {
if (remove) modelMap[existing.cid] = true;
if (merge) {
attrs = attrs === model ? model.attributes : attrs;
if (options.parse) attrs = existing.parse(attrs, options);
existing.set(attrs, options);
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
}
models[i] = existing;
// If this is a new, valid model, push it to the `toAdd` list.
} else if (add) {
model = models[i] = this._prepareModel(attrs, options);
if (!model) continue;
toAdd.push(model);
// Listen to added models' events, and index models for lookup by
// `id` and by `cid`.
model.on('all', this._onModelEvent, this);
this._byId[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
}
if (order) order.push(existing || model);
}
// Remove nonexistent models if appropriate.
if (remove) {
for (i = 0, l = this.length; i < l; ++i) {
if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
}
if (toRemove.length) this.remove(toRemove, options);
}
// See if sorting is needed, update `length` and splice in new models.
if (toAdd.length || (order && order.length)) {
if (sortable) sort = true;
this.length += toAdd.length;
if (at != null) {
for (i = 0, l = toAdd.length; i < l; i++) {
this.models.splice(at + i, 0, toAdd[i]);
}
} else {
if (order) this.models.length = 0;
var orderedModels = order || toAdd;
for (i = 0, l = orderedModels.length; i < l; i++) {
this.models.push(orderedModels[i]);
}
}
}
// Silently sort the collection if appropriate.
if (sort) this.sort({silent: true});
// Unless silenced, it's time to fire all appropriate add/sort events.
if (!options.silent) {
for (i = 0, l = toAdd.length; i < l; i++) {
(model = toAdd[i]).trigger('add', model, this, options);
}
if (sort || (order && order.length)) this.trigger('sort', this, options);
}
// Return the added (or merged) model (or models).
return singular ? models[0] : models;
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any granular `add` or `remove` events. Fires `reset` when finished.
// Useful for bulk operations and optimizations.
reset: function(models, options) {
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i]);
}
options.previousModels = this.models;
this._reset();
models = this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return models;
},
// Add a model to the end of the collection.
push: function(model, options) {
return this.add(model, _.extend({at: this.length}, options));
},
// Remove a model from the end of the collection.
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},
// Add a model to the beginning of the collection.
unshift: function(model, options) {
return this.add(model, _.extend({at: 0}, options));
},
// Remove a model from the beginning of the collection.
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},
// Slice out a sub-array of models from the collection.
slice: function() {
return slice.apply(this.models, arguments);
},
// Get a model from the set by id.
get: function(obj) {
if (obj == null) return void 0;
return this._byId[obj.id] || this._byId[obj.cid] || this._byId[obj];
},
// Get the model at the given index.
at: function(index) {
return this.models[index];
},
// Return models with matching attributes. Useful for simple cases of
// `filter`.
where: function(attrs, first) {
if (_.isEmpty(attrs)) return first ? void 0 : [];
return this[first ? 'find' : 'filter'](function(model) {
for (var key in attrs) {
if (attrs[key] !== model.get(key)) return false;
}
return true;
});
},
// Return the first model with matching attributes. Useful for simple cases
// of `find`.
findWhere: function(attrs) {
return this.where(attrs, true);
},
// Force the collection to re-sort itself. You don't need to call this under
// normal circumstances, as the set will maintain sort order as each item
// is added.
sort: function(options) {
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
options || (options = {});
// Run sort based on type of `comparator`.
if (_.isString(this.comparator) || this.comparator.length === 1) {
this.models = this.sortBy(this.comparator, this);
} else {
this.models.sort(_.bind(this.comparator, this));
}
if (!options.silent) this.trigger('sort', this, options);
return this;
},
// Pluck an attribute from each model in the collection.
pluck: function(attr) {
return _.invoke(this.models, 'get', attr);
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `reset: true` is passed, the response
// data will be passed through the `reset` method instead of `set`.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var success = options.success;
var collection = this;
options.success = function(resp) {
var method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if (success) success(collection, resp, options);
collection.trigger('sync', collection, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Create a new instance of a model in this collection. Add the model to the
// collection immediately, unless `wait: true` is passed, in which case we
// wait for the server to agree.
create: function(model, options) {
options = options ? _.clone(options) : {};
if (!(model = this._prepareModel(model, options))) return false;
if (!options.wait) this.add(model, options);
var collection = this;
var success = options.success;
options.success = function(model, resp, options) {
if (options.wait) collection.add(model, options);
if (success) success(model, resp, options);
};
model.save(null, options);
return model;
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse: function(resp, options) {
return resp;
},
// Create a new collection with an identical list of models as this one.
clone: function() {
return new this.constructor(this.models);
},
// Private method to reset all internal state. Called when the collection
// is first initialized or reset.
_reset: function() {
this.length = 0;
this.models = [];
this._byId = {};
},
// Prepare a hash of attributes (or other model) to be added to this
// collection.
_prepareModel: function(attrs, options) {
if (attrs instanceof Model) {
if (!attrs.collection) attrs.collection = this;
return attrs;
}
options = options ? _.clone(options) : {};
options.collection = this;
var model = new this.model(attrs, options);
if (!model.validationError) return model;
this.trigger('invalid', this, model.validationError, options);
return false;
},
// Internal method to sever a model's ties to a collection.
_removeReference: function(model) {
if (this === model.collection) delete model.collection;
model.off('all', this._onModelEvent, this);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent: function(event, model, collection, options) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(model, options);
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
if (model.id != null) this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
// Underscore methods that we want to implement on the Collection.
// 90% of the core usefulness of Backbone Collections is actually implemented
// right here:
var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
'lastIndexOf', 'isEmpty', 'chain'];
// Mix in each Underscore method as a proxy to `Collection#models`.
_.each(methods, function(method) {
Collection.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.models);
return _[method].apply(_, args);
};
});
// Underscore methods that take a property name as an argument.
var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
// Use attributes instead of properties.
_.each(attributeMethods, function(method) {
Collection.prototype[method] = function(value, context) {
var iterator = _.isFunction(value) ? value : function(model) {
return model.get(value);
};
return _[method](this.models, iterator, context);
};
});
// Backbone.View
// -------------
// Backbone Views are almost more convention than they are actual code. A View
// is simply a JavaScript object that represents a logical chunk of UI in the
// DOM. This might be a single item, an entire list, a sidebar or panel, or
// even the surrounding frame which wraps your whole app. Defining a chunk of
// UI as a **View** allows you to define your DOM events declaratively, without
// having to worry about render order ... and makes it easy for the view to
// react to specific changes in the state of your models.
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
options || (options = {});
_.extend(this, _.pick(options, viewOptions));
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(View.prototype, Events, {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
// jQuery delegate for element lookup, scoped to DOM elements within the
// current view. This should be preferred to global lookups where possible.
$: function(selector) {
return this.$el.find(selector);
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render: function() {
return this;
},
// Remove this view by taking the element out of the DOM, and removing any
// applicable Backbone.Events listeners.
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
// Change the view's element (`this.el` property), including event
// re-delegation.
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save',
// 'click .open': function(e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
// Clears all callbacks previously bound to the view with `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
});
// Backbone.sync
// -------------
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
// as `POST`, with a `_method` parameter containing the true HTTP method,
// as well as all requests with the body as `application/x-www-form-urlencoded`
// instead of `application/json` with the model in a param named `model`.
// Useful when interfacing with server-side languages like **PHP** that make
// it difficult to read the body of `PUT` requests.
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default options, unless specified.
_.defaults(options || (options = {}), {
emulateHTTP: Backbone.emulateHTTP,
emulateJSON: Backbone.emulateJSON
});
// Default JSON-request options.
var params = {type: type, dataType: 'json'};
// Ensure that we have a URL.
if (!options.url) {
params.url = _.result(model, 'url') || urlError();
}
// Ensure that we have the appropriate request data.
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.contentType = 'application/json';
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (options.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {model: params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
params.type = 'POST';
if (options.emulateJSON) params.data._method = type;
var beforeSend = options.beforeSend;
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
if (beforeSend) return beforeSend.apply(this, arguments);
};
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !options.emulateJSON) {
params.processData = false;
}
// If we're sending a `PATCH` request, and we're in an old Internet Explorer
// that still has ActiveX enabled by default, override jQuery to use that
// for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
if (params.type === 'PATCH' && noXhrPatch) {
params.xhr = function() {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
// Make the request, allowing the user to override any Ajax options.
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
model.trigger('request', model, xhr, options);
return xhr;
};
var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch': 'PATCH',
'delete': 'DELETE',
'read': 'GET'
};
// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
// Override this if you'd like to use a different library.
Backbone.ajax = function() {
return Backbone.$.ajax.apply(Backbone.$, arguments);
};
// Backbone.Router
// ---------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);
callback && callback.apply(router, args);
router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
Backbone.history.trigger('route', router, name, args);
});
return this;
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
return this;
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function() {
if (!this.routes) return;
this.routes = _.result(this, 'routes');
var route, routes = _.keys(this.routes);
while ((route = routes.pop()) != null) {
this.route(route, this.routes[route]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^\/]+)';
})
.replace(splatParam, '(.*?)');
return new RegExp('^' + route + '$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted decoded parameters. Empty or unmatched parameters will be
// treated as `null` to normalize cross-browser behavior.
_extractParameters: function(route, fragment) {
var params = route.exec(fragment).slice(1);
return _.map(params, function(param) {
return param ? decodeURIComponent(param) : null;
});
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments. If the browser supports neither (old IE, natch),
// falls back to polling.
var History = Backbone.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
// Ensure that `History` can be used outside of the browser.
if (typeof window !== 'undefined') {
this.location = window.location;
this.history = window.history;
}
};
// Cached regex for stripping a leading hash/slash and trailing space.
var routeStripper = /^[#\/]|\s+$/g;
// Cached regex for stripping leading and trailing slashes.
var rootStripper = /^\/+|\/+$/g;
// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
// Cached regex for removing a trailing slash.
var trailingSlash = /\/$/;
// Cached regex for stripping urls of hash and query.
var pathStripper = /[?#].*$/;
// Has the history handling already been started?
History.started = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(History.prototype, Events, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function(window) {
var match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment: function(fragment, forcePushState) {
if (fragment == null) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = this.location.pathname;
var root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) fragment = fragment.slice(root.length);
} else {
fragment = this.getHash();
}
}
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({root: '/'}, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
// Normalize root to always include a leading and trailing slash.
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
if (oldIE && this._wantsHashChange) {
this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
Backbone.$(window).on('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
Backbone.$(window).on('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = this.location;
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
// Transition from hashChange to pushState or vice versa if both are
// requested.
if (this._wantsHashChange && this._wantsPushState) {
// If we've started off with a route from a `pushState`-enabled
// browser, but we're currently in a browser that doesn't support it...
if (!this._hasPushState && !atRoot) {
this.fragment = this.getFragment(null, true);
this.location.replace(this.root + this.location.search + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._hasPushState && atRoot && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
}
}
if (!this.options.silent) return this.loadUrl();
},
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function() {
Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
clearInterval(this._checkUrlInterval);
History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function(e) {
var current = this.getFragment();
if (current === this.fragment && this.iframe) {
current = this.getFragment(this.getHash(this.iframe));
}
if (current === this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl();
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragment) {
fragment = this.fragment = this.getFragment(fragment);
return _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function(fragment, options) {
if (!History.started) return false;
if (!options || options === true) options = {trigger: !!options};
var url = this.root + (fragment = this.getFragment(fragment || ''));
// Strip the fragment of the query and hash for matching.
fragment = fragment.replace(pathStripper, '');
if (this.fragment === fragment) return;
this.fragment = fragment;
// Don't include a trailing slash on the root.
if (fragment === '' && url !== '/') url = url.slice(0, -1);
// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this._updateHash(this.location, fragment, options.replace);
if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
// Opening and closing the iframe tricks IE7 and earlier to push a
// history entry on hash-tag change. When replace is true, we don't
// want this.
if(!options.replace) this.iframe.document.open().close();
this._updateHash(this.iframe.location, fragment, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
return this.location.assign(url);
}
if (options.trigger) return this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
// Some browsers require that `hash` contains a leading #.
location.hash = '#' + fragment;
}
}
});
// Create the default Backbone.history.
Backbone.history = new History;
// Helpers
// -------
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
// Set up inheritance for the model, collection, router, view and history.
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
// Wrap an optional error callback with a fallback error event.
var wrapError = function(model, options) {
var error = options.error;
options.error = function(resp) {
if (error) error(model, resp, options);
model.trigger('error', model, resp, options);
};
};
return Backbone;
}));
/**
* @license RequireJS text 2.0.10 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/requirejs/text for details
*/
/*jslint regexp: true */
/*global require, XMLHttpRequest, ActiveXObject,
define, window, process, Packages,
java, location, Components, FileUtils */
define('text',['module'], function (module) {
var text, fs, Cc, Ci, xpcIsWindows,
progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,
hasLocation = typeof location !== 'undefined' && location.href,
defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''),
defaultHostName = hasLocation && location.hostname,
defaultPort = hasLocation && (location.port || undefined),
buildMap = {},
masterConfig = (module.config && module.config()) || {};
text = {
version: '2.0.10',
strip: function (content) {
//Strips <?xml ...?> declarations so that external SVG and XML
//documents can be added to a document without worry. Also, if the string
//is an HTML document, only the part inside the body tag is returned.
if (content) {
content = content.replace(xmlRegExp, "");
var matches = content.match(bodyRegExp);
if (matches) {
content = matches[1];
}
} else {
content = "";
}
return content;
},
jsEscape: function (content) {
return content.replace(/(['\\])/g, '\\$1')
.replace(/[\f]/g, "\\f")
.replace(/[\b]/g, "\\b")
.replace(/[\n]/g, "\\n")
.replace(/[\t]/g, "\\t")
.replace(/[\r]/g, "\\r")
.replace(/[\u2028]/g, "\\u2028")
.replace(/[\u2029]/g, "\\u2029");
},
createXhr: masterConfig.createXhr || function () {
//Would love to dump the ActiveX crap in here. Need IE 6 to die first.
var xhr, i, progId;
if (typeof XMLHttpRequest !== "undefined") {
return new XMLHttpRequest();
} else if (typeof ActiveXObject !== "undefined") {
for (i = 0; i < 3; i += 1) {
progId = progIds[i];
try {
xhr = new ActiveXObject(progId);
} catch (e) {}
if (xhr) {
progIds = [progId]; // so faster next time
break;
}
}
}
return xhr;
},
/**
* Parses a resource name into its component parts. Resource names
* look like: module/name.ext!strip, where the !strip part is
* optional.
* @param {String} name the resource name
* @returns {Object} with properties "moduleName", "ext" and "strip"
* where strip is a boolean.
*/
parseName: function (name) {
var modName, ext, temp,
strip = false,
index = name.indexOf("."),
isRelative = name.indexOf('./') === 0 ||
name.indexOf('../') === 0;
if (index !== -1 && (!isRelative || index > 1)) {
modName = name.substring(0, index);
ext = name.substring(index + 1, name.length);
} else {
modName = name;
}
temp = ext || modName;
index = temp.indexOf("!");
if (index !== -1) {
//Pull off the strip arg.
strip = temp.substring(index + 1) === "strip";
temp = temp.substring(0, index);
if (ext) {
ext = temp;
} else {
modName = temp;
}
}
return {
moduleName: modName,
ext: ext,
strip: strip
};
},
xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/,
/**
* Is an URL on another domain. Only works for browser use, returns
* false in non-browser environments. Only used to know if an
* optimized .js version of a text resource should be loaded
* instead.
* @param {String} url
* @returns Boolean
*/
useXhr: function (url, protocol, hostname, port) {
var uProtocol, uHostName, uPort,
match = text.xdRegExp.exec(url);
if (!match) {
return true;
}
uProtocol = match[2];
uHostName = match[3];
uHostName = uHostName.split(':');
uPort = uHostName[1];
uHostName = uHostName[0];
return (!uProtocol || uProtocol === protocol) &&
(!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) &&
((!uPort && !uHostName) || uPort === port);
},
finishLoad: function (name, strip, content, onLoad) {
content = strip ? text.strip(content) : content;
if (masterConfig.isBuild) {
buildMap[name] = content;
}
onLoad(content);
},
load: function (name, req, onLoad, config) {
//Name has format: some.module.filext!strip
//The strip part is optional.
//if strip is present, then that means only get the string contents
//inside a body tag in an HTML string. For XML/SVG content it means
//removing the <?xml ...?> declarations so the content can be inserted
//into the current doc without problems.
// Do not bother with the work if a build and text will
// not be inlined.
if (config.isBuild && !config.inlineText) {
onLoad();
return;
}
masterConfig.isBuild = config.isBuild;
var parsed = text.parseName(name),
nonStripName = parsed.moduleName +
(parsed.ext ? '.' + parsed.ext : ''),
url = req.toUrl(nonStripName),
useXhr = (masterConfig.useXhr) ||
text.useXhr;
// Do not load if it is an empty: url
if (url.indexOf('empty:') === 0) {
onLoad();
return;
}
//Load the text. Use XHR if possible and in a browser.
if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) {
text.get(url, function (content) {
text.finishLoad(name, parsed.strip, content, onLoad);
}, function (err) {
if (onLoad.error) {
onLoad.error(err);
}
});
} else {
//Need to fetch the resource across domains. Assume
//the resource has been optimized into a JS module. Fetch
//by the module name + extension, but do not include the
//!strip part to avoid file system issues.
req([nonStripName], function (content) {
text.finishLoad(parsed.moduleName + '.' + parsed.ext,
parsed.strip, content, onLoad);
});
}
},
write: function (pluginName, moduleName, write, config) {
if (buildMap.hasOwnProperty(moduleName)) {
var content = text.jsEscape(buildMap[moduleName]);
write.asModule(pluginName + "!" + moduleName,
"define(function () { return '" +
content +
"';});\n");
}
},
writeFile: function (pluginName, moduleName, req, write, config) {
var parsed = text.parseName(moduleName),
extPart = parsed.ext ? '.' + parsed.ext : '',
nonStripName = parsed.moduleName + extPart,
//Use a '.js' file name so that it indicates it is a
//script that can be loaded across domains.
fileName = req.toUrl(parsed.moduleName + extPart) + '.js';
//Leverage own load() method to load plugin value, but only
//write out values that do not have the strip argument,
//to avoid any potential issues with ! in file names.
text.load(nonStripName, req, function (value) {
//Use own write() method to construct full module value.
//But need to create shell that translates writeFile's
//write() to the right interface.
var textWrite = function (contents) {
return write(fileName, contents);
};
textWrite.asModule = function (moduleName, contents) {
return write.asModule(moduleName, fileName, contents);
};
text.write(pluginName, nonStripName, textWrite, config);
}, config);
}
};
if (masterConfig.env === 'node' || (!masterConfig.env &&
typeof process !== "undefined" &&
process.versions &&
!!process.versions.node &&
!process.versions['node-webkit'])) {
//Using special require.nodeRequire, something added by r.js.
fs = require.nodeRequire('fs');
text.get = function (url, callback, errback) {
try {
var file = fs.readFileSync(url, 'utf8');
//Remove BOM (Byte Mark Order) from utf8 files if it is there.
if (file.indexOf('\uFEFF') === 0) {
file = file.substring(1);
}
callback(file);
} catch (e) {
errback(e);
}
};
} else if (masterConfig.env === 'xhr' || (!masterConfig.env &&
text.createXhr())) {
text.get = function (url, callback, errback, headers) {
var xhr = text.createXhr(), header;
xhr.open('GET', url, true);
//Allow plugins direct access to xhr headers
if (headers) {
for (header in headers) {
if (headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header.toLowerCase(), headers[header]);
}
}
}
//Allow overrides specified in config
if (masterConfig.onXhr) {
masterConfig.onXhr(xhr, url);
}
xhr.onreadystatechange = function (evt) {
var status, err;
//Do not explicitly handle errors, those should be
//visible via console output in the browser.
if (xhr.readyState === 4) {
status = xhr.status;
if (status > 399 && status < 600) {
//An http 4xx or 5xx error. Signal an error.
err = new Error(url + ' HTTP status: ' + status);
err.xhr = xhr;
errback(err);
} else {
callback(xhr.responseText);
}
if (masterConfig.onXhrComplete) {
masterConfig.onXhrComplete(xhr, url);
}
}
};
xhr.send(null);
};
} else if (masterConfig.env === 'rhino' || (!masterConfig.env &&
typeof Packages !== 'undefined' && typeof java !== 'undefined')) {
//Why Java, why is this so awkward?
text.get = function (url, callback) {
var stringBuffer, line,
encoding = "utf-8",
file = new java.io.File(url),
lineSeparator = java.lang.System.getProperty("line.separator"),
input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
content = '';
try {
stringBuffer = new java.lang.StringBuffer();
line = input.readLine();
// Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
// http://www.unicode.org/faq/utf_bom.html
// Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
if (line && line.length() && line.charAt(0) === 0xfeff) {
// Eat the BOM, since we've already found the encoding on this file,
// and we plan to concatenating this buffer with others; the BOM should
// only appear at the top of a file.
line = line.substring(1);
}
if (line !== null) {
stringBuffer.append(line);
}
while ((line = input.readLine()) !== null) {
stringBuffer.append(lineSeparator);
stringBuffer.append(line);
}
//Make sure we return a JavaScript string and not a Java string.
content = String(stringBuffer.toString()); //String
} finally {
input.close();
}
callback(content);
};
} else if (masterConfig.env === 'xpconnect' || (!masterConfig.env &&
typeof Components !== 'undefined' && Components.classes &&
Components.interfaces)) {
//Avert your gaze!
Cc = Components.classes,
Ci = Components.interfaces;
Components.utils['import']('resource://gre/modules/FileUtils.jsm');
xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc);
text.get = function (url, callback) {
var inStream, convertStream, fileObj,
readData = {};
if (xpcIsWindows) {
url = url.replace(/\//g, '\\');
}
fileObj = new FileUtils.File(url);
//XPCOM, you so crazy
try {
inStream = Cc['@mozilla.org/network/file-input-stream;1']
.createInstance(Ci.nsIFileInputStream);
inStream.init(fileObj, 1, 0, false);
convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
.createInstance(Ci.nsIConverterInputStream);
convertStream.init(inStream, "utf-8", inStream.available(),
Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
convertStream.readString(inStream.available(), readData);
convertStream.close();
inStream.close();
callback(readData.value);
} catch (e) {
throw new Error((fileObj && fileObj.path || '') + ': ' + e);
}
};
}
return text;
});
define('text!tpl/search.html',[],function () { return '<input type="text" class="<%=className%>" value="" placeholder="<%=placeholder%>">';});
define('text!tpl/search_suggestion.html',[],function () { return '<p id="index-<%=idx%>" class="search-suggestion">\n\n <strong><%=name%></strong>\n\n <span class="small">\n <% if (final) { %>\n constant\n <% } else if (itemtype) { %>\n <%=itemtype%> \n <% } %>\n\n <% if (className) { %>\n in <strong><%=className%></strong>\n <% } %>\n\n <% if (is_constructor) { %>\n <strong><span class="glyphicon glyphicon-star"></span> constructor</strong>\n <% } %>\n </span>\n\n</p>';});
/*!
* typeahead.js 0.10.2
* https://github.com/twitter/typeahead.js
* Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
*/
define('typeahead',[], function() {
//(function($) {
var _ = {
isMsie: function() {
return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
},
isBlankString: function(str) {
return !str || /^\s*$/.test(str);
},
escapeRegExChars: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
isString: function(obj) {
return typeof obj === "string";
},
isNumber: function(obj) {
return typeof obj === "number";
},
isArray: $.isArray,
isFunction: $.isFunction,
isObject: $.isPlainObject,
isUndefined: function(obj) {
return typeof obj === "undefined";
},
bind: $.proxy,
each: function(collection, cb) {
$.each(collection, reverseArgs);
function reverseArgs(index, value) {
return cb(value, index);
}
},
map: $.map,
filter: $.grep,
every: function(obj, test) {
var result = true;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (!(result = test.call(null, val, key, obj))) {
return false;
}
});
return !!result;
},
some: function(obj, test) {
var result = false;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (result = test.call(null, val, key, obj)) {
return false;
}
});
return !!result;
},
mixin: $.extend,
getUniqueId: function() {
var counter = 0;
return function() {
return counter++;
};
}(),
templatify: function templatify(obj) {
return $.isFunction(obj) ? obj : template;
function template() {
return String(obj);
}
},
defer: function(fn) {
setTimeout(fn, 0);
},
debounce: function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments, later, callNow;
later = function() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
},
throttle: function(func, wait) {
var context, args, timeout, result, previous, later;
previous = 0;
later = function() {
previous = new Date();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date(), remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
noop: function() {}
};
var VERSION = "0.10.2";
var tokenizers = function(root) {
return {
nonword: nonword,
whitespace: whitespace,
obj: {
nonword: getObjTokenizer(nonword),
whitespace: getObjTokenizer(whitespace)
}
};
function whitespace(s) {
return s.split(/\s+/);
}
function nonword(s) {
return s.split(/\W+/);
}
function getObjTokenizer(tokenizer) {
return function setKey(key) {
return function tokenize(o) {
return tokenizer(o[key]);
};
};
}
}();
var LruCache = function() {
function LruCache(maxSize) {
this.maxSize = maxSize || 100;
this.size = 0;
this.hash = {};
this.list = new List();
}
_.mixin(LruCache.prototype, {
set: function set(key, val) {
var tailItem = this.list.tail, node;
if (this.size >= this.maxSize) {
this.list.remove(tailItem);
delete this.hash[tailItem.key];
}
if (node = this.hash[key]) {
node.val = val;
this.list.moveToFront(node);
} else {
node = new Node(key, val);
this.list.add(node);
this.hash[key] = node;
this.size++;
}
},
get: function get(key) {
var node = this.hash[key];
if (node) {
this.list.moveToFront(node);
return node.val;
}
}
});
function List() {
this.head = this.tail = null;
}
_.mixin(List.prototype, {
add: function add(node) {
if (this.head) {
node.next = this.head;
this.head.prev = node;
}
this.head = node;
this.tail = this.tail || node;
},
remove: function remove(node) {
node.prev ? node.prev.next = node.next : this.head = node.next;
node.next ? node.next.prev = node.prev : this.tail = node.prev;
},
moveToFront: function(node) {
this.remove(node);
this.add(node);
}
});
function Node(key, val) {
this.key = key;
this.val = val;
this.prev = this.next = null;
}
return LruCache;
}();
var PersistentStorage = function() {
var ls, methods;
try {
ls = window.localStorage;
ls.setItem("~~~", "!");
ls.removeItem("~~~");
} catch (err) {
ls = null;
}
function PersistentStorage(namespace) {
this.prefix = [ "__", namespace, "__" ].join("");
this.ttlKey = "__ttl__";
this.keyMatcher = new RegExp("^" + this.prefix);
}
if (ls && window.JSON) {
methods = {
_prefix: function(key) {
return this.prefix + key;
},
_ttlKey: function(key) {
return this._prefix(key) + this.ttlKey;
},
get: function(key) {
if (this.isExpired(key)) {
this.remove(key);
}
return decode(ls.getItem(this._prefix(key)));
},
set: function(key, val, ttl) {
if (_.isNumber(ttl)) {
ls.setItem(this._ttlKey(key), encode(now() + ttl));
} else {
ls.removeItem(this._ttlKey(key));
}
return ls.setItem(this._prefix(key), encode(val));
},
remove: function(key) {
ls.removeItem(this._ttlKey(key));
ls.removeItem(this._prefix(key));
return this;
},
clear: function() {
var i, key, keys = [], len = ls.length;
for (i = 0; i < len; i++) {
if ((key = ls.key(i)).match(this.keyMatcher)) {
keys.push(key.replace(this.keyMatcher, ""));
}
}
for (i = keys.length; i--; ) {
this.remove(keys[i]);
}
return this;
},
isExpired: function(key) {
var ttl = decode(ls.getItem(this._ttlKey(key)));
return _.isNumber(ttl) && now() > ttl ? true : false;
}
};
} else {
methods = {
get: _.noop,
set: _.noop,
remove: _.noop,
clear: _.noop,
isExpired: _.noop
};
}
_.mixin(PersistentStorage.prototype, methods);
return PersistentStorage;
function now() {
return new Date().getTime();
}
function encode(val) {
return JSON.stringify(_.isUndefined(val) ? null : val);
}
function decode(val) {
return JSON.parse(val);
}
}();
var Transport = function() {
var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, requestCache = new LruCache(10);
function Transport(o) {
o = o || {};
this._send = o.transport ? callbackToDeferred(o.transport) : $.ajax;
this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get;
}
Transport.setMaxPendingRequests = function setMaxPendingRequests(num) {
maxPendingRequests = num;
};
Transport.resetCache = function clearCache() {
requestCache = new LruCache(10);
};
_.mixin(Transport.prototype, {
_get: function(url, o, cb) {
var that = this, jqXhr;
if (jqXhr = pendingRequests[url]) {
jqXhr.done(done).fail(fail);
} else if (pendingRequestsCount < maxPendingRequests) {
pendingRequestsCount++;
pendingRequests[url] = this._send(url, o).done(done).fail(fail).always(always);
} else {
this.onDeckRequestArgs = [].slice.call(arguments, 0);
}
function done(resp) {
cb && cb(null, resp);
requestCache.set(url, resp);
}
function fail() {
cb && cb(true);
}
function always() {
pendingRequestsCount--;
delete pendingRequests[url];
if (that.onDeckRequestArgs) {
that._get.apply(that, that.onDeckRequestArgs);
that.onDeckRequestArgs = null;
}
}
},
get: function(url, o, cb) {
var resp;
if (_.isFunction(o)) {
cb = o;
o = {};
}
if (resp = requestCache.get(url)) {
_.defer(function() {
cb && cb(null, resp);
});
} else {
this._get(url, o, cb);
}
return !!resp;
}
});
return Transport;
function callbackToDeferred(fn) {
return function customSendWrapper(url, o) {
var deferred = $.Deferred();
fn(url, o, onSuccess, onError);
return deferred;
function onSuccess(resp) {
_.defer(function() {
deferred.resolve(resp);
});
}
function onError(err) {
_.defer(function() {
deferred.reject(err);
});
}
};
}
}();
var SearchIndex = function() {
function SearchIndex(o) {
o = o || {};
if (!o.datumTokenizer || !o.queryTokenizer) {
$.error("datumTokenizer and queryTokenizer are both required");
}
this.datumTokenizer = o.datumTokenizer;
this.queryTokenizer = o.queryTokenizer;
this.reset();
}
_.mixin(SearchIndex.prototype, {
bootstrap: function bootstrap(o) {
this.datums = o.datums;
this.trie = o.trie;
},
add: function(data) {
var that = this;
data = _.isArray(data) ? data : [ data ];
_.each(data, function(datum) {
var id, tokens;
id = that.datums.push(datum) - 1;
tokens = normalizeTokens(that.datumTokenizer(datum));
_.each(tokens, function(token) {
var node, chars, ch;
node = that.trie;
chars = token.split("");
while (ch = chars.shift()) {
node = node.children[ch] || (node.children[ch] = newNode());
node.ids.push(id);
}
});
});
},
get: function get(query) {
var that = this, tokens, matches;
tokens = normalizeTokens(this.queryTokenizer(query));
_.each(tokens, function(token) {
var node, chars, ch, ids;
if (matches && matches.length === 0) {
return false;
}
node = that.trie;
chars = token.split("");
while (node && (ch = chars.shift())) {
node = node.children[ch];
}
if (node && chars.length === 0) {
ids = node.ids.slice(0);
matches = matches ? getIntersection(matches, ids) : ids;
} else {
matches = [];
return false;
}
});
return matches ? _.map(unique(matches), function(id) {
return that.datums[id];
}) : [];
},
reset: function reset() {
this.datums = [];
this.trie = newNode();
},
serialize: function serialize() {
return {
datums: this.datums,
trie: this.trie
};
}
});
return SearchIndex;
function normalizeTokens(tokens) {
tokens = _.filter(tokens, function(token) {
return !!token;
});
tokens = _.map(tokens, function(token) {
return token.toLowerCase();
});
return tokens;
}
function newNode() {
return {
ids: [],
children: {}
};
}
function unique(array) {
var seen = {}, uniques = [];
for (var i = 0; i < array.length; i++) {
if (!seen[array[i]]) {
seen[array[i]] = true;
uniques.push(array[i]);
}
}
return uniques;
}
function getIntersection(arrayA, arrayB) {
var ai = 0, bi = 0, intersection = [];
arrayA = arrayA.sort(compare);
arrayB = arrayB.sort(compare);
while (ai < arrayA.length && bi < arrayB.length) {
if (arrayA[ai] < arrayB[bi]) {
ai++;
} else if (arrayA[ai] > arrayB[bi]) {
bi++;
} else {
intersection.push(arrayA[ai]);
ai++;
bi++;
}
}
return intersection;
function compare(a, b) {
return a - b;
}
}
}();
var oParser = function() {
return {
local: getLocal,
prefetch: getPrefetch,
remote: getRemote
};
function getLocal(o) {
return o.local || null;
}
function getPrefetch(o) {
var prefetch, defaults;
defaults = {
url: null,
thumbprint: "",
ttl: 24 * 60 * 60 * 1e3,
filter: null,
ajax: {}
};
if (prefetch = o.prefetch || null) {
prefetch = _.isString(prefetch) ? {
url: prefetch
} : prefetch;
prefetch = _.mixin(defaults, prefetch);
prefetch.thumbprint = VERSION + prefetch.thumbprint;
prefetch.ajax.type = prefetch.ajax.type || "GET";
prefetch.ajax.dataType = prefetch.ajax.dataType || "json";
!prefetch.url && $.error("prefetch requires url to be set");
}
return prefetch;
}
function getRemote(o) {
var remote, defaults;
defaults = {
url: null,
wildcard: "%QUERY",
replace: null,
rateLimitBy: "debounce",
rateLimitWait: 300,
send: null,
filter: null,
ajax: {}
};
if (remote = o.remote || null) {
remote = _.isString(remote) ? {
url: remote
} : remote;
remote = _.mixin(defaults, remote);
remote.rateLimiter = /^throttle$/i.test(remote.rateLimitBy) ? byThrottle(remote.rateLimitWait) : byDebounce(remote.rateLimitWait);
remote.ajax.type = remote.ajax.type || "GET";
remote.ajax.dataType = remote.ajax.dataType || "json";
delete remote.rateLimitBy;
delete remote.rateLimitWait;
!remote.url && $.error("remote requires url to be set");
}
return remote;
function byDebounce(wait) {
return function(fn) {
return _.debounce(fn, wait);
};
}
function byThrottle(wait) {
return function(fn) {
return _.throttle(fn, wait);
};
}
}
}();
(function(root) {
var old, keys;
old = root.Bloodhound;
keys = {
data: "data",
protocol: "protocol",
thumbprint: "thumbprint"
};
root.Bloodhound = Bloodhound;
function Bloodhound(o) {
if (!o || !o.local && !o.prefetch && !o.remote) {
$.error("one of local, prefetch, or remote is required");
}
this.limit = o.limit || 5;
this.sorter = getSorter(o.sorter);
this.dupDetector = o.dupDetector || ignoreDuplicates;
this.local = oParser.local(o);
this.prefetch = oParser.prefetch(o);
this.remote = oParser.remote(o);
this.cacheKey = this.prefetch ? this.prefetch.cacheKey || this.prefetch.url : null;
this.index = new SearchIndex({
datumTokenizer: o.datumTokenizer,
queryTokenizer: o.queryTokenizer
});
this.storage = this.cacheKey ? new PersistentStorage(this.cacheKey) : null;
}
Bloodhound.noConflict = function noConflict() {
root.Bloodhound = old;
return Bloodhound;
};
Bloodhound.tokenizers = tokenizers;
_.mixin(Bloodhound.prototype, {
_loadPrefetch: function loadPrefetch(o) {
var that = this, serialized, deferred;
if (serialized = this._readFromStorage(o.thumbprint)) {
this.index.bootstrap(serialized);
deferred = $.Deferred().resolve();
} else {
deferred = $.ajax(o.url, o.ajax).done(handlePrefetchResponse);
}
return deferred;
function handlePrefetchResponse(resp) {
that.clear();
that.add(o.filter ? o.filter(resp) : resp);
that._saveToStorage(that.index.serialize(), o.thumbprint, o.ttl);
}
},
_getFromRemote: function getFromRemote(query, cb) {
var that = this, url, uriEncodedQuery;
query = query || "";
uriEncodedQuery = encodeURIComponent(query);
url = this.remote.replace ? this.remote.replace(this.remote.url, query) : this.remote.url.replace(this.remote.wildcard, uriEncodedQuery);
return this.transport.get(url, this.remote.ajax, handleRemoteResponse);
function handleRemoteResponse(err, resp) {
err ? cb([]) : cb(that.remote.filter ? that.remote.filter(resp) : resp);
}
},
_saveToStorage: function saveToStorage(data, thumbprint, ttl) {
if (this.storage) {
this.storage.set(keys.data, data, ttl);
this.storage.set(keys.protocol, location.protocol, ttl);
this.storage.set(keys.thumbprint, thumbprint, ttl);
}
},
_readFromStorage: function readFromStorage(thumbprint) {
var stored = {}, isExpired;
if (this.storage) {
stored.data = this.storage.get(keys.data);
stored.protocol = this.storage.get(keys.protocol);
stored.thumbprint = this.storage.get(keys.thumbprint);
}
isExpired = stored.thumbprint !== thumbprint || stored.protocol !== location.protocol;
return stored.data && !isExpired ? stored.data : null;
},
_initialize: function initialize() {
var that = this, local = this.local, deferred;
deferred = this.prefetch ? this._loadPrefetch(this.prefetch) : $.Deferred().resolve();
local && deferred.done(addLocalToIndex);
this.transport = this.remote ? new Transport(this.remote) : null;
return this.initPromise = deferred.promise();
function addLocalToIndex() {
that.add(_.isFunction(local) ? local() : local);
}
},
initialize: function initialize(force) {
return !this.initPromise || force ? this._initialize() : this.initPromise;
},
add: function add(data) {
this.index.add(data);
},
get: function get(query, cb) {
var that = this, matches = [], cacheHit = false;
matches = this.index.get(query);
matches = this.sorter(matches).slice(0, this.limit);
if (matches.length < this.limit && this.transport) {
cacheHit = this._getFromRemote(query, returnRemoteMatches);
}
if (!cacheHit) {
(matches.length > 0 || !this.transport) && cb && cb(matches);
}
function returnRemoteMatches(remoteMatches) {
var matchesWithBackfill = matches.slice(0);
_.each(remoteMatches, function(remoteMatch) {
var isDuplicate;
isDuplicate = _.some(matchesWithBackfill, function(match) {
return that.dupDetector(remoteMatch, match);
});
!isDuplicate && matchesWithBackfill.push(remoteMatch);
return matchesWithBackfill.length < that.limit;
});
cb && cb(that.sorter(matchesWithBackfill));
}
},
clear: function clear() {
this.index.reset();
},
clearPrefetchCache: function clearPrefetchCache() {
this.storage && this.storage.clear();
},
clearRemoteCache: function clearRemoteCache() {
this.transport && Transport.resetCache();
},
ttAdapter: function ttAdapter() {
return _.bind(this.get, this);
}
});
return Bloodhound;
function getSorter(sortFn) {
return _.isFunction(sortFn) ? sort : noSort;
function sort(array) {
return array.sort(sortFn);
}
function noSort(array) {
return array;
}
}
function ignoreDuplicates() {
return false;
}
})(this);
var html = {
wrapper: '<span class="twitter-typeahead"></span>',
dropdown: '<span class="tt-dropdown-menu"></span>',
dataset: '<div class="tt-dataset-%CLASS%"></div>',
suggestions: '<span class="tt-suggestions"></span>',
suggestion: '<div class="tt-suggestion"></div>'
};
var css = {
wrapper: {
position: "relative",
display: "inline-block"
},
hint: {
position: "absolute",
top: "0",
left: "0",
borderColor: "transparent",
boxShadow: "none"
},
input: {
position: "relative",
verticalAlign: "top",
backgroundColor: "transparent"
},
inputWithNoHint: {
position: "relative",
verticalAlign: "top"
},
dropdown: {
position: "absolute",
top: "100%",
left: "0",
zIndex: "100",
display: "none"
},
suggestions: {
display: "block"
},
suggestion: {
whiteSpace: "nowrap",
cursor: "pointer"
},
suggestionChild: {
whiteSpace: "normal"
},
ltr: {
left: "0",
right: "auto"
},
rtl: {
left: "auto",
right: " 0"
}
};
if (_.isMsie()) {
_.mixin(css.input, {
backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
});
}
if (_.isMsie() && _.isMsie() <= 7) {
_.mixin(css.input, {
marginTop: "-1px"
});
}
var EventBus = function() {
var namespace = "typeahead:";
function EventBus(o) {
if (!o || !o.el) {
$.error("EventBus initialized without el");
}
this.$el = $(o.el);
}
_.mixin(EventBus.prototype, {
trigger: function(type) {
var args = [].slice.call(arguments, 1);
this.$el.trigger(namespace + type, args);
}
});
return EventBus;
}();
var EventEmitter = function() {
var splitter = /\s+/, nextTick = getNextTick();
return {
onSync: onSync,
onAsync: onAsync,
off: off,
trigger: trigger
};
function on(method, types, cb, context) {
var type;
if (!cb) {
return this;
}
types = types.split(splitter);
cb = context ? bindContext(cb, context) : cb;
this._callbacks = this._callbacks || {};
while (type = types.shift()) {
this._callbacks[type] = this._callbacks[type] || {
sync: [],
async: []
};
this._callbacks[type][method].push(cb);
}
return this;
}
function onAsync(types, cb, context) {
return on.call(this, "async", types, cb, context);
}
function onSync(types, cb, context) {
return on.call(this, "sync", types, cb, context);
}
function off(types) {
var type;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
while (type = types.shift()) {
delete this._callbacks[type];
}
return this;
}
function trigger(types) {
var type, callbacks, args, syncFlush, asyncFlush;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
args = [].slice.call(arguments, 1);
while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args));
asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args));
syncFlush() && nextTick(asyncFlush);
}
return this;
}
function getFlush(callbacks, context, args) {
return flush;
function flush() {
var cancelled;
for (var i = 0; !cancelled && i < callbacks.length; i += 1) {
cancelled = callbacks[i].apply(context, args) === false;
}
return !cancelled;
}
}
function getNextTick() {
var nextTickFn;
if (window.setImmediate) {
nextTickFn = function nextTickSetImmediate(fn) {
setImmediate(function() {
fn();
});
};
} else {
nextTickFn = function nextTickSetTimeout(fn) {
setTimeout(function() {
fn();
}, 0);
};
}
return nextTickFn;
}
function bindContext(fn, context) {
return fn.bind ? fn.bind(context) : function() {
fn.apply(context, [].slice.call(arguments, 0));
};
}
}();
var highlight = function(doc) {
var defaults = {
node: null,
pattern: null,
tagName: "strong",
className: null,
wordsOnly: false,
caseSensitive: false
};
return function hightlight(o) {
var regex;
o = _.mixin({}, defaults, o);
if (!o.node || !o.pattern) {
return;
}
o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ];
regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
traverse(o.node, hightlightTextNode);
function hightlightTextNode(textNode) {
var match, patternNode;
if (match = regex.exec(textNode.data)) {
wrapperNode = doc.createElement(o.tagName);
o.className && (wrapperNode.className = o.className);
patternNode = textNode.splitText(match.index);
patternNode.splitText(match[0].length);
wrapperNode.appendChild(patternNode.cloneNode(true));
textNode.parentNode.replaceChild(wrapperNode, patternNode);
}
return !!match;
}
function traverse(el, hightlightTextNode) {
var childNode, TEXT_NODE_TYPE = 3;
for (var i = 0; i < el.childNodes.length; i++) {
childNode = el.childNodes[i];
if (childNode.nodeType === TEXT_NODE_TYPE) {
i += hightlightTextNode(childNode) ? 1 : 0;
} else {
traverse(childNode, hightlightTextNode);
}
}
}
};
function getRegex(patterns, caseSensitive, wordsOnly) {
var escapedPatterns = [], regexStr;
for (var i = 0; i < patterns.length; i++) {
escapedPatterns.push(_.escapeRegExChars(patterns[i]));
}
regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
}
}(window.document);
var Input = function() {
var specialKeyCodeMap;
specialKeyCodeMap = {
9: "tab",
27: "esc",
37: "left",
39: "right",
13: "enter",
38: "up",
40: "down"
};
function Input(o) {
var that = this, onBlur, onFocus, onKeydown, onInput;
o = o || {};
if (!o.input) {
$.error("input is missing");
}
onBlur = _.bind(this._onBlur, this);
onFocus = _.bind(this._onFocus, this);
onKeydown = _.bind(this._onKeydown, this);
onInput = _.bind(this._onInput, this);
this.$hint = $(o.hint);
this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
if (this.$hint.length === 0) {
this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
}
if (!_.isMsie()) {
this.$input.on("input.tt", onInput);
} else {
this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
if (specialKeyCodeMap[$e.which || $e.keyCode]) {
return;
}
_.defer(_.bind(that._onInput, that, $e));
});
}
this.query = this.$input.val();
this.$overflowHelper = buildOverflowHelper(this.$input);
}
Input.normalizeQuery = function(str) {
return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
};
_.mixin(Input.prototype, EventEmitter, {
_onBlur: function onBlur() {
this.resetInputValue();
this.trigger("blurred");
},
_onFocus: function onFocus() {
this.trigger("focused");
},
_onKeydown: function onKeydown($e) {
var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
this._managePreventDefault(keyName, $e);
if (keyName && this._shouldTrigger(keyName, $e)) {
this.trigger(keyName + "Keyed", $e);
}
},
_onInput: function onInput() {
this._checkInputValue();
},
_managePreventDefault: function managePreventDefault(keyName, $e) {
var preventDefault, hintValue, inputValue;
switch (keyName) {
case "tab":
hintValue = this.getHint();
inputValue = this.getInputValue();
preventDefault = hintValue && hintValue !== inputValue && !withModifier($e);
break;
case "up":
case "down":
preventDefault = !withModifier($e);
break;
default:
preventDefault = false;
}
preventDefault && $e.preventDefault();
},
_shouldTrigger: function shouldTrigger(keyName, $e) {
var trigger;
switch (keyName) {
case "tab":
trigger = !withModifier($e);
break;
default:
trigger = true;
}
return trigger;
},
_checkInputValue: function checkInputValue() {
var inputValue, areEquivalent, hasDifferentWhitespace;
inputValue = this.getInputValue();
areEquivalent = areQueriesEquivalent(inputValue, this.query);
hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
if (!areEquivalent) {
this.trigger("queryChanged", this.query = inputValue);
} else if (hasDifferentWhitespace) {
this.trigger("whitespaceChanged", this.query);
}
},
focus: function focus() {
this.$input.focus();
},
blur: function blur() {
this.$input.blur();
},
getQuery: function getQuery() {
return this.query;
},
setQuery: function setQuery(query) {
this.query = query;
},
getInputValue: function getInputValue() {
return this.$input.val();
},
setInputValue: function setInputValue(value, silent) {
this.$input.val(value);
silent ? this.clearHint() : this._checkInputValue();
},
resetInputValue: function resetInputValue() {
this.setInputValue(this.query, true);
},
getHint: function getHint() {
return this.$hint.val();
},
setHint: function setHint(value) {
this.$hint.val(value);
},
clearHint: function clearHint() {
this.setHint("");
},
clearHintIfInvalid: function clearHintIfInvalid() {
var val, hint, valIsPrefixOfHint, isValid;
val = this.getInputValue();
hint = this.getHint();
valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
!isValid && this.clearHint();
},
getLanguageDirection: function getLanguageDirection() {
return (this.$input.css("direction") || "ltr").toLowerCase();
},
hasOverflow: function hasOverflow() {
var constraint = this.$input.width() - 2;
this.$overflowHelper.text(this.getInputValue());
return this.$overflowHelper.width() >= constraint;
},
isCursorAtEnd: function() {
var valueLength, selectionStart, range;
valueLength = this.$input.val().length;
selectionStart = this.$input[0].selectionStart;
if (_.isNumber(selectionStart)) {
return selectionStart === valueLength;
} else if (document.selection) {
range = document.selection.createRange();
range.moveStart("character", -valueLength);
return valueLength === range.text.length;
}
return true;
},
destroy: function destroy() {
this.$hint.off(".tt");
this.$input.off(".tt");
this.$hint = this.$input = this.$overflowHelper = null;
}
});
return Input;
function buildOverflowHelper($input) {
return $('<pre aria-hidden="true"></pre>').css({
position: "absolute",
visibility: "hidden",
whiteSpace: "pre",
fontFamily: $input.css("font-family"),
fontSize: $input.css("font-size"),
fontStyle: $input.css("font-style"),
fontVariant: $input.css("font-variant"),
fontWeight: $input.css("font-weight"),
wordSpacing: $input.css("word-spacing"),
letterSpacing: $input.css("letter-spacing"),
textIndent: $input.css("text-indent"),
textRendering: $input.css("text-rendering"),
textTransform: $input.css("text-transform")
}).insertAfter($input);
}
function areQueriesEquivalent(a, b) {
return Input.normalizeQuery(a) === Input.normalizeQuery(b);
}
function withModifier($e) {
return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
}
}();
var Dataset = function() {
var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
function Dataset(o) {
o = o || {};
o.templates = o.templates || {};
if (!o.source) {
$.error("missing source");
}
if (o.name && !isValidName(o.name)) {
$.error("invalid dataset name: " + o.name);
}
this.query = null;
this.highlight = !!o.highlight;
this.name = o.name || _.getUniqueId();
this.source = o.source;
this.displayFn = getDisplayFn(o.display || o.displayKey);
this.templates = getTemplates(o.templates, this.displayFn);
this.$el = $(html.dataset.replace("%CLASS%", this.name));
}
Dataset.extractDatasetName = function extractDatasetName(el) {
return $(el).data(datasetKey);
};
Dataset.extractValue = function extractDatum(el) {
return $(el).data(valueKey);
};
Dataset.extractDatum = function extractDatum(el) {
return $(el).data(datumKey);
};
_.mixin(Dataset.prototype, EventEmitter, {
_render: function render(query, suggestions) {
if (!this.$el) {
return;
}
var that = this, hasSuggestions;
this.$el.empty();
hasSuggestions = suggestions && suggestions.length;
if (!hasSuggestions && this.templates.empty) {
this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
} else if (hasSuggestions) {
this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
}
this.trigger("rendered");
function getEmptyHtml() {
return that.templates.empty({
query: query,
isEmpty: true
});
}
function getSuggestionsHtml() {
var $suggestions, nodes;
$suggestions = $(html.suggestions).css(css.suggestions);
nodes = _.map(suggestions, getSuggestionNode);
$suggestions.append.apply($suggestions, nodes);
that.highlight && highlight({
node: $suggestions[0],
pattern: query
});
return $suggestions;
function getSuggestionNode(suggestion) {
var $el;
$el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
$el.children().each(function() {
$(this).css(css.suggestionChild);
});
return $el;
}
}
function getHeaderHtml() {
return that.templates.header({
query: query,
isEmpty: !hasSuggestions
});
}
function getFooterHtml() {
return that.templates.footer({
query: query,
isEmpty: !hasSuggestions
});
}
},
getRoot: function getRoot() {
return this.$el;
},
update: function update(query) {
var that = this;
this.query = query;
this.canceled = false;
this.source(query, render);
function render(suggestions) {
if (!that.canceled && query === that.query) {
that._render(query, suggestions);
}
}
},
cancel: function cancel() {
this.canceled = true;
},
clear: function clear() {
this.cancel();
this.$el.empty();
this.trigger("rendered");
},
isEmpty: function isEmpty() {
return this.$el.is(":empty");
},
destroy: function destroy() {
this.$el = null;
}
});
return Dataset;
function getDisplayFn(display) {
display = display || "value";
return _.isFunction(display) ? display : displayFn;
function displayFn(obj) {
return obj[display];
}
}
function getTemplates(templates, displayFn) {
return {
empty: templates.empty && _.templatify(templates.empty),
header: templates.header && _.templatify(templates.header),
footer: templates.footer && _.templatify(templates.footer),
suggestion: templates.suggestion || suggestionTemplate
};
function suggestionTemplate(context) {
return "<p>" + displayFn(context) + "</p>";
}
}
function isValidName(str) {
return /^[_a-zA-Z0-9-]+$/.test(str);
}
}();
var Dropdown = function() {
function Dropdown(o) {
var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
o = o || {};
if (!o.menu) {
$.error("menu is required");
}
this.isOpen = false;
this.isEmpty = true;
this.datasets = _.map(o.datasets, initializeDataset);
onSuggestionClick = _.bind(this._onSuggestionClick, this);
onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
this.$menu = $(o.menu).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave);
_.each(this.datasets, function(dataset) {
that.$menu.append(dataset.getRoot());
dataset.onSync("rendered", that._onRendered, that);
});
}
_.mixin(Dropdown.prototype, EventEmitter, {
_onSuggestionClick: function onSuggestionClick($e) {
this.trigger("suggestionClicked", $($e.currentTarget));
},
_onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
this._removeCursor();
this._setCursor($($e.currentTarget), true);
},
_onSuggestionMouseLeave: function onSuggestionMouseLeave() {
this._removeCursor();
},
_onRendered: function onRendered() {
this.isEmpty = _.every(this.datasets, isDatasetEmpty);
this.isEmpty ? this._hide() : this.isOpen && this._show();
this.trigger("datasetRendered");
function isDatasetEmpty(dataset) {
return dataset.isEmpty();
}
},
_hide: function() {
this.$menu.hide();
},
_show: function() {
this.$menu.css("display", "block");
},
_getSuggestions: function getSuggestions() {
return this.$menu.find(".tt-suggestion");
},
_getCursor: function getCursor() {
return this.$menu.find(".tt-cursor").first();
},
_setCursor: function setCursor($el, silent) {
$el.first().addClass("tt-cursor");
!silent && this.trigger("cursorMoved");
},
_removeCursor: function removeCursor() {
this._getCursor().removeClass("tt-cursor");
},
_moveCursor: function moveCursor(increment) {
var $suggestions, $oldCursor, newCursorIndex, $newCursor;
if (!this.isOpen) {
return;
}
$oldCursor = this._getCursor();
$suggestions = this._getSuggestions();
this._removeCursor();
newCursorIndex = $suggestions.index($oldCursor) + increment;
newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
if (newCursorIndex === -1) {
this.trigger("cursorRemoved");
return;
} else if (newCursorIndex < -1) {
newCursorIndex = $suggestions.length - 1;
}
this._setCursor($newCursor = $suggestions.eq(newCursorIndex));
this._ensureVisible($newCursor);
},
_ensureVisible: function ensureVisible($el) {
var elTop, elBottom, menuScrollTop, menuHeight;
elTop = $el.position().top;
elBottom = elTop + $el.outerHeight(true);
menuScrollTop = this.$menu.scrollTop();
menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10);
if (elTop < 0) {
this.$menu.scrollTop(menuScrollTop + elTop);
} else if (menuHeight < elBottom) {
this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
}
},
close: function close() {
if (this.isOpen) {
this.isOpen = false;
this._removeCursor();
this._hide();
this.trigger("closed");
}
},
open: function open() {
if (!this.isOpen) {
this.isOpen = true;
!this.isEmpty && this._show();
this.trigger("opened");
}
},
setLanguageDirection: function setLanguageDirection(dir) {
this.$menu.css(dir === "ltr" ? css.ltr : css.rtl);
},
moveCursorUp: function moveCursorUp() {
this._moveCursor(-1);
},
moveCursorDown: function moveCursorDown() {
this._moveCursor(+1);
},
getDatumForSuggestion: function getDatumForSuggestion($el) {
var datum = null;
if ($el.length) {
datum = {
raw: Dataset.extractDatum($el),
value: Dataset.extractValue($el),
datasetName: Dataset.extractDatasetName($el)
};
}
return datum;
},
getDatumForCursor: function getDatumForCursor() {
return this.getDatumForSuggestion(this._getCursor().first());
},
getDatumForTopSuggestion: function getDatumForTopSuggestion() {
return this.getDatumForSuggestion(this._getSuggestions().first());
},
update: function update(query) {
_.each(this.datasets, updateDataset);
function updateDataset(dataset) {
dataset.update(query);
}
},
empty: function empty() {
_.each(this.datasets, clearDataset);
this.isEmpty = true;
function clearDataset(dataset) {
dataset.clear();
}
},
isVisible: function isVisible() {
return this.isOpen && !this.isEmpty;
},
destroy: function destroy() {
this.$menu.off(".tt");
this.$menu = null;
_.each(this.datasets, destroyDataset);
function destroyDataset(dataset) {
dataset.destroy();
}
}
});
return Dropdown;
function initializeDataset(oDataset) {
return new Dataset(oDataset);
}
}();
var Typeahead = function() {
var attrsKey = "ttAttrs";
function Typeahead(o) {
var $menu, $input, $hint;
o = o || {};
if (!o.input) {
$.error("missing input");
}
this.isActivated = false;
this.autoselect = !!o.autoselect;
this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
this.$node = buildDomStructure(o.input, o.withHint);
$menu = this.$node.find(".tt-dropdown-menu");
$input = this.$node.find(".tt-input");
$hint = this.$node.find(".tt-hint");
$input.on("blur.tt", function($e) {
var active, isActive, hasActive;
active = document.activeElement;
isActive = $menu.is(active);
hasActive = $menu.has(active).length > 0;
if (_.isMsie() && (isActive || hasActive)) {
$e.preventDefault();
$e.stopImmediatePropagation();
_.defer(function() {
$input.focus();
});
}
});
$menu.on("mousedown.tt", function($e) {
$e.preventDefault();
});
this.eventBus = o.eventBus || new EventBus({
el: $input
});
this.dropdown = new Dropdown({
menu: $menu,
datasets: o.datasets
}).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this);
this.input = new Input({
input: $input,
hint: $hint
}).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this);
this._setLanguageDirection();
}
_.mixin(Typeahead.prototype, {
_onSuggestionClicked: function onSuggestionClicked(type, $el) {
var datum;
if (datum = this.dropdown.getDatumForSuggestion($el)) {
this._select(datum);
}
},
_onCursorMoved: function onCursorMoved() {
var datum = this.dropdown.getDatumForCursor();
this.input.setInputValue(datum.value, true);
this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName);
},
_onCursorRemoved: function onCursorRemoved() {
this.input.resetInputValue();
this._updateHint();
},
_onDatasetRendered: function onDatasetRendered() {
this._updateHint();
},
_onOpened: function onOpened() {
this._updateHint();
this.eventBus.trigger("opened");
},
_onClosed: function onClosed() {
this.input.clearHint();
this.eventBus.trigger("closed");
},
_onFocused: function onFocused() {
this.isActivated = true;
this.dropdown.open();
},
_onBlurred: function onBlurred() {
this.isActivated = false;
this.dropdown.empty();
this.dropdown.close();
this.setVal("", true); //LM
},
_onEnterKeyed: function onEnterKeyed(type, $e) {
var cursorDatum, topSuggestionDatum;
cursorDatum = this.dropdown.getDatumForCursor();
topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();
if (cursorDatum) {
this._select(cursorDatum);
$e.preventDefault();
} else if (this.autoselect && topSuggestionDatum) {
this._select(topSuggestionDatum);
$e.preventDefault();
}
},
_onTabKeyed: function onTabKeyed(type, $e) {
var datum;
if (datum = this.dropdown.getDatumForCursor()) {
this._select(datum);
$e.preventDefault();
} else {
this._autocomplete(true);
}
},
_onEscKeyed: function onEscKeyed() {
this.dropdown.close();
this.input.resetInputValue();
},
_onUpKeyed: function onUpKeyed() {
var query = this.input.getQuery();
this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorUp();
this.dropdown.open();
},
_onDownKeyed: function onDownKeyed() {
var query = this.input.getQuery();
this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorDown();
this.dropdown.open();
},
_onLeftKeyed: function onLeftKeyed() {
this.dir === "rtl" && this._autocomplete();
},
_onRightKeyed: function onRightKeyed() {
this.dir === "ltr" && this._autocomplete();
},
_onQueryChanged: function onQueryChanged(e, query) {
this.input.clearHintIfInvalid();
query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.empty();
this.dropdown.open();
this._setLanguageDirection();
},
_onWhitespaceChanged: function onWhitespaceChanged() {
this._updateHint();
this.dropdown.open();
},
_setLanguageDirection: function setLanguageDirection() {
var dir;
if (this.dir !== (dir = this.input.getLanguageDirection())) {
this.dir = dir;
this.$node.css("direction", dir);
this.dropdown.setLanguageDirection(dir);
}
},
_updateHint: function updateHint() {
var datum, val, query, escapedQuery, frontMatchRegEx, match;
datum = this.dropdown.getDatumForTopSuggestion();
if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
val = this.input.getInputValue();
query = Input.normalizeQuery(val);
escapedQuery = _.escapeRegExChars(query);
frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
match = frontMatchRegEx.exec(datum.value);
match ? this.input.setHint(val + match[1]) : this.input.clearHint();
} else {
this.input.clearHint();
}
},
_autocomplete: function autocomplete(laxCursor) {
var hint, query, isCursorAtEnd, datum;
hint = this.input.getHint();
query = this.input.getQuery();
isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
if (hint && query !== hint && isCursorAtEnd) {
datum = this.dropdown.getDatumForTopSuggestion();
datum && this.input.setInputValue(datum.value);
this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName);
}
},
_select: function select(datum) {
this.input.setQuery(datum.value);
this.input.setInputValue(datum.value, true);
this._setLanguageDirection();
this.eventBus.trigger("selected", datum.raw, datum.datasetName);
this.dropdown.close();
_.defer(_.bind(this.dropdown.empty, this.dropdown));
},
open: function open() {
this.dropdown.open();
},
close: function close() {
this.dropdown.close();
},
setVal: function setVal(val) {
if (this.isActivated) {
this.input.setInputValue(val);
} else {
this.input.setQuery(val);
this.input.setInputValue(val, true);
}
this._setLanguageDirection();
},
getVal: function getVal() {
return this.input.getQuery();
},
destroy: function destroy() {
this.input.destroy();
this.dropdown.destroy();
destroyDomStructure(this.$node);
this.$node = null;
}
});
return Typeahead;
function buildDomStructure(input, withHint) {
var $input, $wrapper, $dropdown, $hint;
$input = $(input);
$wrapper = $(html.wrapper).css(css.wrapper);
$dropdown = $(html.dropdown).css(css.dropdown);
$hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
$hint.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder").prop("disabled", true).attr({
autocomplete: "off",
spellcheck: "false"
});
$input.data(attrsKey, {
dir: $input.attr("dir"),
autocomplete: $input.attr("autocomplete"),
spellcheck: $input.attr("spellcheck"),
style: $input.attr("style")
});
$input.addClass("tt-input").attr({
autocomplete: "off",
spellcheck: false
}).css(withHint ? css.input : css.inputWithNoHint);
try {
!$input.attr("dir") && $input.attr("dir", "auto");
} catch (e) {}
return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown);
}
function getBackgroundStyles($el) {
return {
backgroundAttachment: $el.css("background-attachment"),
backgroundClip: $el.css("background-clip"),
backgroundColor: $el.css("background-color"),
backgroundImage: $el.css("background-image"),
backgroundOrigin: $el.css("background-origin"),
backgroundPosition: $el.css("background-position"),
backgroundRepeat: $el.css("background-repeat"),
backgroundSize: $el.css("background-size")
};
}
function destroyDomStructure($node) {
var $input = $node.find(".tt-input");
_.each($input.data(attrsKey), function(val, key) {
_.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
});
$input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node);
$node.remove();
}
}();
(function() {
var old, typeaheadKey, methods;
old = $.fn.typeahead;
typeaheadKey = "ttTypeahead";
methods = {
initialize: function initialize(o, datasets) {
datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
o = o || {};
return this.each(attach);
function attach() {
var $input = $(this), eventBus, typeahead;
_.each(datasets, function(d) {
d.highlight = !!o.highlight;
});
typeahead = new Typeahead({
input: $input,
eventBus: eventBus = new EventBus({
el: $input
}),
withHint: _.isUndefined(o.hint) ? true : !!o.hint,
minLength: o.minLength,
autoselect: o.autoselect,
datasets: datasets
});
$input.data(typeaheadKey, typeahead);
}
},
open: function open() {
return this.each(openTypeahead);
function openTypeahead() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.open();
}
}
},
close: function close() {
return this.each(closeTypeahead);
function closeTypeahead() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.close();
}
}
},
val: function val(newVal) {
return !arguments.length ? getVal(this.first()) : this.each(setVal);
function setVal() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.setVal(newVal);
}
}
function getVal($input) {
var typeahead, query;
if (typeahead = $input.data(typeaheadKey)) {
query = typeahead.getVal();
}
return query;
}
},
destroy: function destroy() {
return this.each(unattach);
function unattach() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.destroy();
$input.removeData(typeaheadKey);
}
}
}
};
$.fn.typeahead = function(method) {
if (methods[method]) {
return methods[method].apply(this, [].slice.call(arguments, 1));
} else {
return methods.initialize.apply(this, arguments);
}
};
$.fn.typeahead.noConflict = function noConflict() {
$.fn.typeahead = old;
return this;
};
})();
//})(window.jQuery);
});
define('searchView',[
'underscore',
'backbone',
'App',
// Templates
'text!tpl/search.html',
'text!tpl/search_suggestion.html',
// Tools
'typeahead'
], function(_, Backbone, App, searchTpl, suggestionTpl) {
var searchView = Backbone.View.extend({
el: '#search',
/**
* Init.
*/
init: function() {
var tpl = _.template(searchTpl);
var className = 'form-control input-lg';
var placeholder = 'Search the API';
this.searchHtml = tpl({
'placeholder': placeholder,
'className': className
});
this.items = App.classes.concat(App.allItems);
return this;
},
/**
* Render input field with Typehead activated.
*/
render: function() {
// Append the view to the dom
this.$el.append(this.searchHtml);
// Render Typeahead
var $searchInput = this.$el.find('input[type=text]');
this.typeaheadRender($searchInput);
this.typeaheadEvents($searchInput);
return this;
},
/**
* Apply Twitter Typeahead to the search input field.
* @param {jquery} $input
*/
typeaheadRender: function($input) {
var self = this;
$input.typeahead(null, {
'displayKey': 'name',
'minLength': 2,
//'highlight': true,
'source': self.substringMatcher(this.items),
'templates': {
'empty': '<p class="empty-message">Unable to find any item that match the current query</p>',
'suggestion': _.template(suggestionTpl)
}
});
},
/**
* Setup typeahead custom events (item selected).
*/
typeaheadEvents: function($input) {
var self = this;
$input.on('typeahead:selected', function(e, item, datasetName) {
var selectedItem = self.items[item.idx];
select(selectedItem);
});
$input.on('keydown', function(e) {
if (e.which === 13) { // enter
var txt = $input.val();
var f = _.find(self.items, function(it) { return it.name == txt; });
if (f) {
select(f);
}
} else if (e.which === 27) {
$input.blur();
}
});
function select(selectedItem) {
var hash = App.router.getHash(selectedItem).replace('#', '');
App.router.navigate(hash, {'trigger': true});
$input.blur();
}
},
/**
* substringMatcher function for Typehead (search for strings in an array).
* @param {array} array
* @returns {Function}
*/
substringMatcher: function(array) {
return function findMatches(query, callback) {
var matches = [], substrRegex, arrayLength = array.length;
// regex used to determine if a string contains the substring `query`
substrRegex = new RegExp(query, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `query`, add it to the `matches` array
for (var i=0; i < arrayLength; i++) {
var item = array[i];
if (substrRegex.test(item.name)) {
// typeahead expects suggestions to be a js object
matches.push({
'itemtype': item.itemtype,
'name': item.name,
'className': item.class,
'is_constructor': item.is_constructor,
'final': item.final,
'idx': i
});
}
}
callback(matches);
};
}
});
return searchView;
});
define('text!tpl/list.html',[],function () { return '<!-- <div class="page-header">\n <h1>\n <%=title%>\n </h1>\n</div> -->\n\n<% _.each(groups, function(group){ %>\n <h4 class="group-name" id="group-<%=group.name%>"><%=group.name%></h4>\n <div class="reference-group clearfix main-ref-page"> \n <% _.each(group.subgroups, function(subgroup, ind) { %>\n <dl>\n <% if (subgroup.name !== \'0\') { %>\n <dt class="subgroup-<%=subgroup.name%>"><%=subgroup.name%></dt>\n <% } %>\n <% _.each(subgroup.items, function(item) { %>\n <dd><a href="<%=item.hash%>"><%=item.name%><% if (item.itemtype === \'method\') { %>()<%}%></a></dd>\n <% }); %>\n </dl>\n <% }); %>\n </div>\n<% }); %>\n\n\n\n \n ';});
define('listView',[
'underscore',
'backbone',
'App',
// Templates
'text!tpl/list.html'
], function (_, Backbone, App, listTpl) {
var listView = Backbone.View.extend({
el: '#list',
events: {},
/**
* Init.
*/
init: function () {
this.listTpl = _.template(listTpl);
return this;
},
/**
* Render the list.
*/
render: function (items, listCollection) {
if (items && listCollection) {
var self = this;
// Render items and group them by module
// module === group
this.groups = {};
_.each(items, function (item, i) {
if (item.file.indexOf('addons') === -1) { //addons don't get displayed on main page
var group = item.module || '_';
var subgroup = item.submodule || '_';
if (group === subgroup) {
subgroup = '0';
}
var hash = App.router.getHash(item);
// Create a group list
if (!self.groups[group]) {
self.groups[group] = {
name: group.replace('_', ' '),
subgroups: {}
};
}
// Create a subgroup list
if (!self.groups[group].subgroups[subgroup]) {
self.groups[group].subgroups[subgroup] = {
name: subgroup.replace('_', ' '),
items: []
};
}
if (item.file.indexOf('objects') === -1) {
self.groups[group].subgroups[subgroup].items.push(item);
} else {
var found = _.find(self.groups[group].subgroups[subgroup].items,
function(i){ return i.name == item.class; });
if (!found) {
var hash = item.hash;
var ind = hash.lastIndexOf('/');
hash = hash.substring(0, ind);
self.groups[group].subgroups[subgroup].items.push({
name: item.class,
hash: hash
});
}
}
}
});
// Put the <li> items html into the list <ul>
var listHtml = self.listTpl({
'title': self.capitalizeFirst(listCollection),
'groups': self.groups,
'listCollection': listCollection
});
// Render the view
this.$el.html(listHtml);
}
return this;
},
/**
* Show a list of items.
* @param {array} items Array of item objects.
* @returns {object} This view.
*/
show: function (listGroup) {
if (App[listGroup]) {
this.render(App[listGroup], listGroup);
}
App.pageView.hideContentViews();
this.$el.show();
return this;
},
/**
* Helper method to capitalize the first letter of a string
* @param {string} str
* @returns {string} Returns the string.
*/
capitalizeFirst: function (str) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
});
return listView;
});
define('text!tpl/item.html',[],function () { return '<h3><%=item.name%><% if (item.isMethod) { %>()<% } %></h3>\n\n<% if (item.example) { %>\n<div class="example">\n <h4>Example</h4>\n\n\t<div class="example-content">\n <%= item.example %>\n </div>\n</div> \n<% } %>\n\n\n<div class="description">\n <h4>Description</h4>\n <p><%= item.description %></p>\n</div>\n\n\n<div>\n <h4>Syntax</h4>\n<p><pre><code class="language-javascript"><%= syntax %></code></pre></p>\n</div>\n\n\n<% if (item.return) { %>\n<span class="returns-inline">\n <span class="type"></span>\n</span>\n<% } %>\n\n<% if (item.deprecated) { %>\n<span class="flag deprecated"<% if (item.deprecationMessage) { %> title="<%=item.deprecationMessage%>"<% } %>>deprecated</span>\n<% } %>\n\n<% if (item.access) { %>\n<span class="flag <%=item.access%>"><%= item.access %></span>\n<% } %>\n\n<% if (item.final) { %>\n<span class="flag final">final</span>\n<% } %>\n\n<% if (item.static) { %>\n<span class="flag static">static</span>\n<% } %>\n\n<% if (item.chainable) { %>\n<span class="label label-success chainable">chainable</span>\n<% } %>\n\n<% if (item.async) { %>\n<span class="flag async">async</span>\n<% } %>\n\n<!-- <div class="meta">\n {{#if overwritten_from}}\n <p>Inherited from\n <a href="#">\n {{overwritten_from/class}}\n </a>\n {{#if foundAt}}\n but overwritten in\n {{/if}}\n {{else}}\n {{#if extended_from}}\n <p>Inherited from\n <a href="#">{{extended_from}}</a>:\n {{else}}\n {{#providedBy}}\n <p>Provided by the <a href="../modules/{{.}}.html">{{.}}</a> module.</p>\n {{/providedBy}}\n <p>\n {{#if foundAt}}\n Defined in\n {{/if}}\n {{/if}}\n {{/if}}\n {{#if foundAt}}\n <a href="{{foundAt}}">`{{{file}}}:{{{line}}}`</a>\n {{/if}}\n </p>\n\n {{#if deprecationMessage}}\n <p>Deprecated: {{deprecationMessage}}</p>\n {{/if}}\n\n {{#if since}}\n <p>Available since {{since}}</p>\n {{/if}}\n </div>-->\n\n<% if (item.params) { %>\n<div class="params">\n <h4>Parameters</h4>\n <ul>\n <% for (var i=0; i<item.params.length; i++) { %>\n <li>\n <% var p = item.params[i] %>\n <% if (p.optional) { %>\n <code class="language-javascript">[<%=p.name%>]</code>\n <% } else { %>\n <code class="language-javascript"><%=p.name%></code>\n <% } %> \n <%if (p.optdefault) { %>=<%=p.optdefault%><% } %>\n <% if (p.type) { %>\n <span class="param-type label label-info"><%=p.type%></span>: <%=p.description%></span> \n <% } %>\n <% if (p.multiple) {%>\n <span class="flag multiple" title="This argument may occur one or more times.">multiple</span>\n <% } %>\n </li>\n <% } %>\n </ul>\n</div>\n<% } %>\n\n<% if (item.return) { %>\n<div>\n <h4>Returns</h4>\n\n <% if (item.return.type) { %>\n <p><span class="param-type label label-info"><%=item.return.type%></span>: <%= item.return.description %></p>\n <% } %>\n</div>\n<% } %>\n\n';});
define('text!tpl/class.html',[],function () { return '\n<% if (is_constructor) { %>\n<div class="constructor">\n <!--<h2>Constructor</h2>--> \n <%=constructor%>\n</div>\n<% } %>\n\n<% var fields = _.filter(things, function(item) { return item.itemtype === \'property\' }); %>\n<% if (fields.length > 0) { %>\n <h4>Fields</h4>\n <p>\n <% _.each(fields, function(item) { %>\n <a href="<%=item.hash%>" <% if (item.module !== module) { %>class="addon"<% } %> ><%=item.name%></a>: <%= item.description %>\n <br>\n <% }); %>\n </p>\n<% } %>\n\n<% var methods = _.filter(things, function(item) { return item.itemtype === \'method\' }); %>\n<% if (methods.length > 0) { %>\n <h4>Methods</h4>\n <p>\n <% _.each(methods, function(item) { %>\n <a href="<%=item.hash%>" <% if (item.module !== module) { %>class="addon"<% } %>><%=item.name%><% if (item.itemtype === \'method\') { %>()<%}%></a>: <%= item.description %>\n <br>\n <% }); %>\n </p>\n<% } %>';});
define('text!tpl/itemEnd.html',[],function () { return '<p>\n\n <div class="meta">\n <% if (item.class) { %>\n <p>Class: \n <strong><a href=\'#/<%=item.class%>\'><%=item.class%></a></strong></p>\n <% } %>\n\n </div>\n\n\n\n <a style="border-bottom:none !important;" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target=_blank><img src="http://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png" style="width:88px"/></a>\n\n</p>';});
// Copyright (C) 2006 Google 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.
/**
* @fileoverview
* some functions for browser-side pretty printing of code contained in html.
*
* <p>
* For a fairly comprehensive set of languages see the
* <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a>
* file that came with this source. At a minimum, the lexer should work on a
* number of languages including C and friends, Java, Python, Bash, SQL, HTML,
* XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk
* and a subset of Perl, but, because of commenting conventions, doesn't work on
* Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
* <p>
* Usage: <ol>
* <li> include this source file in an html page via
* {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
* <li> define style rules. See the example page for examples.
* <li> mark the {@code <pre>} and {@code <code>} tags in your source with
* {@code class=prettyprint.}
* You can also use the (html deprecated) {@code <xmp>} tag, but the pretty
* printer needs to do more substantial DOM manipulations to support that, so
* some css styles may not be preserved.
* </ol>
* That's it. I wanted to keep the API as simple as possible, so there's no
* need to specify which language the code is in, but if you wish, you can add
* another class to the {@code <pre>} or {@code <code>} element to specify the
* language, as in {@code <pre class="prettyprint lang-java">}. Any class that
* starts with "lang-" followed by a file extension, specifies the file type.
* See the "lang-*.js" files in this directory for code that implements
* per-language file handlers.
* <p>
* Change log:<br>
* cbeust, 2006/08/22
* <blockquote>
* Java annotations (start with "@") are now captured as literals ("lit")
* </blockquote>
* @requires console
*/
// JSLint declarations
/*global console, document, navigator, setTimeout, window, define */
/** @define {boolean} */
var IN_GLOBAL_SCOPE = true;
/**
* Split {@code prettyPrint} into multiple timeouts so as not to interfere with
* UI events.
* If set to {@code false}, {@code prettyPrint()} is synchronous.
*/
window['PR_SHOULD_USE_CONTINUATION'] = true;
/**
* Pretty print a chunk of code.
* @param {string} sourceCodeHtml The HTML to pretty print.
* @param {string} opt_langExtension The language name to use.
* Typically, a filename extension like 'cpp' or 'java'.
* @param {number|boolean} opt_numberLines True to number lines,
* or the 1-indexed number of the first line in sourceCodeHtml.
* @return {string} code as html, but prettier
*/
var prettyPrintOne;
/**
* Find all the {@code <pre>} and {@code <code>} tags in the DOM with
* {@code class=prettyprint} and prettify them.
*
* @param {Function} opt_whenDone called when prettifying is done.
* @param {HTMLElement|HTMLDocument} opt_root an element or document
* containing all the elements to pretty print.
* Defaults to {@code document.body}.
*/
var prettyPrint;
(function () {
var win = window;
// Keyword lists for various languages.
// We use things that coerce to strings to make them compact when minified
// and to defeat aggressive optimizers that fold large string constants.
var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," +
"double,enum,extern,float,goto,inline,int,long,register,short,signed," +
"sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];
var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
"new,operator,private,protected,public,this,throw,true,try,typeof"];
var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignof,align_union,asm,axiom,bool," +
"concept,concept_map,const_cast,constexpr,decltype,delegate," +
"dynamic_cast,explicit,export,friend,generic,late_check," +
"mutable,namespace,nullptr,property,reinterpret_cast,static_assert," +
"static_cast,template,typeid,typename,using,virtual,where"];
var JAVA_KEYWORDS = [COMMON_KEYWORDS,
"abstract,assert,boolean,byte,extends,final,finally,implements,import," +
"instanceof,interface,null,native,package,strictfp,super,synchronized," +
"throws,transient"];
var CSHARP_KEYWORDS = [JAVA_KEYWORDS,
"as,base,by,checked,decimal,delegate,descending,dynamic,event," +
"fixed,foreach,from,group,implicit,in,internal,into,is,let," +
"lock,object,out,override,orderby,params,partial,readonly,ref,sbyte," +
"sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort," +
"var,virtual,where"];
var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
"for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
"throw,true,try,unless,until,when,while,yes";
var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
"debugger,eval,export,function,get,null,set,undefined,var,with," +
"Infinity,NaN"];
var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
"goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
"sub,undef,unless,until,use,wantarray,while,BEGIN,END";
var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
"elif,except,exec,finally,from,global,import,in,is,lambda," +
"nonlocal,not,or,pass,print,raise,try,with,yield," +
"False,True,None"];
var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
"def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
"rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
"BEGIN,END"];
var RUST_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "as,assert,const,copy,drop," +
"enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv," +
"pub,pure,ref,self,static,struct,true,trait,type,unsafe,use"];
var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
"function,in,local,set,then,until"];
var ALL_KEYWORDS = [
CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS,
PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
// token style names. correspond to css classes
/**
* token style for a string literal
* @const
*/
var PR_STRING = 'str';
/**
* token style for a keyword
* @const
*/
var PR_KEYWORD = 'kwd';
/**
* token style for a comment
* @const
*/
var PR_COMMENT = 'com';
/**
* token style for a type
* @const
*/
var PR_TYPE = 'typ';
/**
* token style for a literal value. e.g. 1, null, true.
* @const
*/
var PR_LITERAL = 'lit';
/**
* token style for a punctuation string.
* @const
*/
var PR_PUNCTUATION = 'pun';
/**
* token style for plain text.
* @const
*/
var PR_PLAIN = 'pln';
/**
* token style for an sgml tag.
* @const
*/
var PR_TAG = 'tag';
/**
* token style for a markup declaration such as a DOCTYPE.
* @const
*/
var PR_DECLARATION = 'dec';
/**
* token style for embedded source.
* @const
*/
var PR_SOURCE = 'src';
/**
* token style for an sgml attribute name.
* @const
*/
var PR_ATTRIB_NAME = 'atn';
/**
* token style for an sgml attribute value.
* @const
*/
var PR_ATTRIB_VALUE = 'atv';
/**
* A class that indicates a section of markup that is not code, e.g. to allow
* embedding of line numbers within code listings.
* @const
*/
var PR_NOCODE = 'nocode';
/**
* A set of tokens that can precede a regular expression literal in
* javascript
* http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html
* has the full list, but I've removed ones that might be problematic when
* seen in languages that don't support regular expression literals.
*
* <p>Specifically, I've removed any keywords that can't precede a regexp
* literal in a syntactically legal javascript program, and I've removed the
* "in" keyword since it's not a keyword in many languages, and might be used
* as a count of inches.
*
* <p>The link above does not accurately describe EcmaScript rules since
* it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
* very well in practice.
*
* @private
* @const
*/
var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*';
// CAVEAT: this does not properly handle the case where a regular
// expression immediately follows another since a regular expression may
// have flags for case-sensitivity and the like. Having regexp tokens
// adjacent is not valid in any language I'm aware of, so I'm punting.
// TODO: maybe style special characters inside a regexp as punctuation.
/**
* Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
* matches the union of the sets of strings matched by the input RegExp.
* Since it matches globally, if the input strings have a start-of-input
* anchor (/^.../), it is ignored for the purposes of unioning.
* @param {Array.<RegExp>} regexs non multiline, non-global regexs.
* @return {RegExp} a global regex.
*/
function combinePrefixPatterns(regexs) {
var capturedGroupIndex = 0;
var needToFoldCase = false;
var ignoreCase = false;
for (var i = 0, n = regexs.length; i < n; ++i) {
var regex = regexs[i];
if (regex.ignoreCase) {
ignoreCase = true;
} else if (/[a-z]/i.test(regex.source.replace(
/\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
needToFoldCase = true;
ignoreCase = false;
break;
}
}
var escapeCharToCodeUnit = {
'b': 8,
't': 9,
'n': 0xa,
'v': 0xb,
'f': 0xc,
'r': 0xd
};
function decodeEscape(charsetPart) {
var cc0 = charsetPart.charCodeAt(0);
if (cc0 !== 92 /* \\ */) {
return cc0;
}
var c1 = charsetPart.charAt(1);
cc0 = escapeCharToCodeUnit[c1];
if (cc0) {
return cc0;
} else if ('0' <= c1 && c1 <= '7') {
return parseInt(charsetPart.substring(1), 8);
} else if (c1 === 'u' || c1 === 'x') {
return parseInt(charsetPart.substring(2), 16);
} else {
return charsetPart.charCodeAt(1);
}
}
function encodeEscape(charCode) {
if (charCode < 0x20) {
return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
}
var ch = String.fromCharCode(charCode);
return (ch === '\\' || ch === '-' || ch === ']' || ch === '^')
? "\\" + ch : ch;
}
function caseFoldCharset(charSet) {
var charsetParts = charSet.substring(1, charSet.length - 1).match(
new RegExp(
'\\\\u[0-9A-Fa-f]{4}'
+ '|\\\\x[0-9A-Fa-f]{2}'
+ '|\\\\[0-3][0-7]{0,2}'
+ '|\\\\[0-7]{1,2}'
+ '|\\\\[\\s\\S]'
+ '|-'
+ '|[^-\\\\]',
'g'));
var ranges = [];
var inverse = charsetParts[0] === '^';
var out = ['['];
if (inverse) { out.push('^'); }
for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
var p = charsetParts[i];
if (/\\[bdsw]/i.test(p)) { // Don't muck with named groups.
out.push(p);
} else {
var start = decodeEscape(p);
var end;
if (i + 2 < n && '-' === charsetParts[i + 1]) {
end = decodeEscape(charsetParts[i + 2]);
i += 2;
} else {
end = start;
}
ranges.push([start, end]);
// If the range might intersect letters, then expand it.
// This case handling is too simplistic.
// It does not deal with non-latin case folding.
// It works for latin source code identifiers though.
if (!(end < 65 || start > 122)) {
if (!(end < 65 || start > 90)) {
ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
}
if (!(end < 97 || start > 122)) {
ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
}
}
}
}
// [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
// -> [[1, 12], [14, 14], [16, 17]]
ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); });
var consolidatedRanges = [];
var lastRange = [];
for (var i = 0; i < ranges.length; ++i) {
var range = ranges[i];
if (range[0] <= lastRange[1] + 1) {
lastRange[1] = Math.max(lastRange[1], range[1]);
} else {
consolidatedRanges.push(lastRange = range);
}
}
for (var i = 0; i < consolidatedRanges.length; ++i) {
var range = consolidatedRanges[i];
out.push(encodeEscape(range[0]));
if (range[1] > range[0]) {
if (range[1] + 1 > range[0]) { out.push('-'); }
out.push(encodeEscape(range[1]));
}
}
out.push(']');
return out.join('');
}
function allowAnywhereFoldCaseAndRenumberGroups(regex) {
// Split into character sets, escape sequences, punctuation strings
// like ('(', '(?:', ')', '^'), and runs of characters that do not
// include any of the above.
var parts = regex.source.match(
new RegExp(
'(?:'
+ '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set
+ '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape
+ '|\\\\x[A-Fa-f0-9]{2}' // a hex escape
+ '|\\\\[0-9]+' // a back-reference or octal escape
+ '|\\\\[^ux0-9]' // other escape sequence
+ '|\\(\\?[:!=]' // start of a non-capturing group
+ '|[\\(\\)\\^]' // start/end of a group, or line start
+ '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters
+ ')',
'g'));
var n = parts.length;
// Maps captured group numbers to the number they will occupy in
// the output or to -1 if that has not been determined, or to
// undefined if they need not be capturing in the output.
var capturedGroups = [];
// Walk over and identify back references to build the capturedGroups
// mapping.
for (var i = 0, groupIndex = 0; i < n; ++i) {
var p = parts[i];
if (p === '(') {
// groups are 1-indexed, so max group index is count of '('
++groupIndex;
} else if ('\\' === p.charAt(0)) {
var decimalValue = +p.substring(1);
if (decimalValue) {
if (decimalValue <= groupIndex) {
capturedGroups[decimalValue] = -1;
} else {
// Replace with an unambiguous escape sequence so that
// an octal escape sequence does not turn into a backreference
// to a capturing group from an earlier regex.
parts[i] = encodeEscape(decimalValue);
}
}
}
}
// Renumber groups and reduce capturing groups to non-capturing groups
// where possible.
for (var i = 1; i < capturedGroups.length; ++i) {
if (-1 === capturedGroups[i]) {
capturedGroups[i] = ++capturedGroupIndex;
}
}
for (var i = 0, groupIndex = 0; i < n; ++i) {
var p = parts[i];
if (p === '(') {
++groupIndex;
if (!capturedGroups[groupIndex]) {
parts[i] = '(?:';
}
} else if ('\\' === p.charAt(0)) {
var decimalValue = +p.substring(1);
if (decimalValue && decimalValue <= groupIndex) {
parts[i] = '\\' + capturedGroups[decimalValue];
}
}
}
// Remove any prefix anchors so that the output will match anywhere.
// ^^ really does mean an anchored match though.
for (var i = 0; i < n; ++i) {
if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
}
// Expand letters to groups to handle mixing of case-sensitive and
// case-insensitive patterns if necessary.
if (regex.ignoreCase && needToFoldCase) {
for (var i = 0; i < n; ++i) {
var p = parts[i];
var ch0 = p.charAt(0);
if (p.length >= 2 && ch0 === '[') {
parts[i] = caseFoldCharset(p);
} else if (ch0 !== '\\') {
// TODO: handle letters in numeric escapes.
parts[i] = p.replace(
/[a-zA-Z]/g,
function (ch) {
var cc = ch.charCodeAt(0);
return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
});
}
}
}
return parts.join('');
}
var rewritten = [];
for (var i = 0, n = regexs.length; i < n; ++i) {
var regex = regexs[i];
if (regex.global || regex.multiline) { throw new Error('' + regex); }
rewritten.push(
'(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
}
return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
}
/**
* Split markup into a string of source code and an array mapping ranges in
* that string to the text nodes in which they appear.
*
* <p>
* The HTML DOM structure:</p>
* <pre>
* (Element "p"
* (Element "b"
* (Text "print ")) ; #1
* (Text "'Hello '") ; #2
* (Element "br") ; #3
* (Text " + 'World';")) ; #4
* </pre>
* <p>
* corresponds to the HTML
* {@code <p><b>print </b>'Hello '<br> + 'World';</p>}.</p>
*
* <p>
* It will produce the output:</p>
* <pre>
* {
* sourceCode: "print 'Hello '\n + 'World';",
* // 1 2
* // 012345678901234 5678901234567
* spans: [0, #1, 6, #2, 14, #3, 15, #4]
* }
* </pre>
* <p>
* where #1 is a reference to the {@code "print "} text node above, and so
* on for the other text nodes.
* </p>
*
* <p>
* The {@code} spans array is an array of pairs. Even elements are the start
* indices of substrings, and odd elements are the text nodes (or BR elements)
* that contain the text for those substrings.
* Substrings continue until the next index or the end of the source.
* </p>
*
* @param {Node} node an HTML DOM subtree containing source-code.
* @param {boolean} isPreformatted true if white-space in text nodes should
* be considered significant.
* @return {Object} source code and the text nodes in which they occur.
*/
function extractSourceSpans(node, isPreformatted) {
var nocode = /(?:^|\s)nocode(?:\s|$)/;
var chunks = [];
var length = 0;
var spans = [];
var k = 0;
function walk(node) {
var type = node.nodeType;
if (type == 1) { // Element
if (nocode.test(node.className)) { return; }
for (var child = node.firstChild; child; child = child.nextSibling) {
walk(child);
}
var nodeName = node.nodeName.toLowerCase();
if ('br' === nodeName || 'li' === nodeName) {
chunks[k] = '\n';
spans[k << 1] = length++;
spans[(k++ << 1) | 1] = node;
}
} else if (type == 3 || type == 4) { // Text
var text = node.nodeValue;
if (text.length) {
if (!isPreformatted) {
text = text.replace(/[ \t\r\n]+/g, ' ');
} else {
text = text.replace(/\r\n?/g, '\n'); // Normalize newlines.
}
// TODO: handle tabs here?
chunks[k] = text;
spans[k << 1] = length;
length += text.length;
spans[(k++ << 1) | 1] = node;
}
}
}
walk(node);
return {
sourceCode: chunks.join('').replace(/\n$/, ''),
spans: spans
};
}
/**
* Apply the given language handler to sourceCode and add the resulting
* decorations to out.
* @param {number} basePos the index of sourceCode within the chunk of source
* whose decorations are already present on out.
*/
function appendDecorations(basePos, sourceCode, langHandler, out) {
if (!sourceCode) { return; }
var job = {
sourceCode: sourceCode,
basePos: basePos
};
langHandler(job);
out.push.apply(out, job.decorations);
}
var notWs = /\S/;
/**
* Given an element, if it contains only one child element and any text nodes
* it contains contain only space characters, return the sole child element.
* Otherwise returns undefined.
* <p>
* This is meant to return the CODE element in {@code <pre><code ...>} when
* there is a single child element that contains all the non-space textual
* content, but not to return anything where there are multiple child elements
* as in {@code <pre><code>...</code><code>...</code></pre>} or when there
* is textual content.
*/
function childContentWrapper(element) {
var wrapper = undefined;
for (var c = element.firstChild; c; c = c.nextSibling) {
var type = c.nodeType;
wrapper = (type === 1) // Element Node
? (wrapper ? element : c)
: (type === 3) // Text Node
? (notWs.test(c.nodeValue) ? element : wrapper)
: wrapper;
}
return wrapper === element ? undefined : wrapper;
}
/** Given triples of [style, pattern, context] returns a lexing function,
* The lexing function interprets the patterns to find token boundaries and
* returns a decoration list of the form
* [index_0, style_0, index_1, style_1, ..., index_n, style_n]
* where index_n is an index into the sourceCode, and style_n is a style
* constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
* all characters in sourceCode[index_n-1:index_n].
*
* The stylePatterns is a list whose elements have the form
* [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
*
* Style is a style constant like PR_PLAIN, or can be a string of the
* form 'lang-FOO', where FOO is a language extension describing the
* language of the portion of the token in $1 after pattern executes.
* E.g., if style is 'lang-lisp', and group 1 contains the text
* '(hello (world))', then that portion of the token will be passed to the
* registered lisp handler for formatting.
* The text before and after group 1 will be restyled using this decorator
* so decorators should take care that this doesn't result in infinite
* recursion. For example, the HTML lexer rule for SCRIPT elements looks
* something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match
* '<script>foo()<\/script>', which would cause the current decorator to
* be called with '<script>' which would not match the same rule since
* group 1 must not be empty, so it would be instead styled as PR_TAG by
* the generic tag rule. The handler registered for the 'js' extension would
* then be called with 'foo()', and finally, the current decorator would
* be called with '<\/script>' which would not match the original rule and
* so the generic tag rule would identify it as a tag.
*
* Pattern must only match prefixes, and if it matches a prefix, then that
* match is considered a token with the same style.
*
* Context is applied to the last non-whitespace, non-comment token
* recognized.
*
* Shortcut is an optional string of characters, any of which, if the first
* character, gurantee that this pattern and only this pattern matches.
*
* @param {Array} shortcutStylePatterns patterns that always start with
* a known character. Must have a shortcut string.
* @param {Array} fallthroughStylePatterns patterns that will be tried in
* order if the shortcut ones fail. May have shortcuts.
*
* @return {function (Object)} a
* function that takes source code and returns a list of decorations.
*/
function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
var shortcuts = {};
var tokenizer;
(function () {
var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
var allRegexs = [];
var regexKeys = {};
for (var i = 0, n = allPatterns.length; i < n; ++i) {
var patternParts = allPatterns[i];
var shortcutChars = patternParts[3];
if (shortcutChars) {
for (var c = shortcutChars.length; --c >= 0;) {
shortcuts[shortcutChars.charAt(c)] = patternParts;
}
}
var regex = patternParts[1];
var k = '' + regex;
if (!regexKeys.hasOwnProperty(k)) {
allRegexs.push(regex);
regexKeys[k] = null;
}
}
allRegexs.push(/[\0-\uffff]/);
tokenizer = combinePrefixPatterns(allRegexs);
})();
var nPatterns = fallthroughStylePatterns.length;
/**
* Lexes job.sourceCode and produces an output array job.decorations of
* style classes preceded by the position at which they start in
* job.sourceCode in order.
*
* @param {Object} job an object like <pre>{
* sourceCode: {string} sourceText plain text,
* basePos: {int} position of job.sourceCode in the larger chunk of
* sourceCode.
* }</pre>
*/
var decorate = function (job) {
var sourceCode = job.sourceCode, basePos = job.basePos;
/** Even entries are positions in source in ascending order. Odd enties
* are style markers (e.g., PR_COMMENT) that run from that position until
* the end.
* @type {Array.<number|string>}
*/
var decorations = [basePos, PR_PLAIN];
var pos = 0; // index into sourceCode
var tokens = sourceCode.match(tokenizer) || [];
var styleCache = {};
for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
var token = tokens[ti];
var style = styleCache[token];
var match = void 0;
var isEmbedded;
if (typeof style === 'string') {
isEmbedded = false;
} else {
var patternParts = shortcuts[token.charAt(0)];
if (patternParts) {
match = token.match(patternParts[1]);
style = patternParts[0];
} else {
for (var i = 0; i < nPatterns; ++i) {
patternParts = fallthroughStylePatterns[i];
match = token.match(patternParts[1]);
if (match) {
style = patternParts[0];
break;
}
}
if (!match) { // make sure that we make progress
style = PR_PLAIN;
}
}
isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
if (isEmbedded && !(match && typeof match[1] === 'string')) {
isEmbedded = false;
style = PR_SOURCE;
}
if (!isEmbedded) { styleCache[token] = style; }
}
var tokenStart = pos;
pos += token.length;
if (!isEmbedded) {
decorations.push(basePos + tokenStart, style);
} else { // Treat group 1 as an embedded block of source code.
var embeddedSource = match[1];
var embeddedSourceStart = token.indexOf(embeddedSource);
var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
if (match[2]) {
// If embeddedSource can be blank, then it would match at the
// beginning which would cause us to infinitely recurse on the
// entire token, so we catch the right context in match[2].
embeddedSourceEnd = token.length - match[2].length;
embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
}
var lang = style.substring(5);
// Decorate the left of the embedded source
appendDecorations(
basePos + tokenStart,
token.substring(0, embeddedSourceStart),
decorate, decorations);
// Decorate the embedded source
appendDecorations(
basePos + tokenStart + embeddedSourceStart,
embeddedSource,
langHandlerForExtension(lang, embeddedSource),
decorations);
// Decorate the right of the embedded section
appendDecorations(
basePos + tokenStart + embeddedSourceEnd,
token.substring(embeddedSourceEnd),
decorate, decorations);
}
}
job.decorations = decorations;
};
return decorate;
}
/** returns a function that produces a list of decorations from source text.
*
* This code treats ", ', and ` as string delimiters, and \ as a string
* escape. It does not recognize perl's qq() style strings.
* It has no special handling for double delimiter escapes as in basic, or
* the tripled delimiters used in python, but should work on those regardless
* although in those cases a single string literal may be broken up into
* multiple adjacent string literals.
*
* It recognizes C, C++, and shell style comments.
*
* @param {Object} options a set of optional parameters.
* @return {function (Object)} a function that examines the source code
* in the input job and builds the decoration list.
*/
function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
if (options['tripleQuotedStrings']) {
// '''multi-line-string''', 'single-line-string', and double-quoted
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
null, '\'"']);
} else if (options['multiLineStrings']) {
// 'multi-line-string', "multi-line-string"
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
null, '\'"`']);
} else {
// 'single-line-string', "single-line-string"
shortcutStylePatterns.push(
[PR_STRING,
/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
null, '"\'']);
}
if (options['verbatimStrings']) {
// verbatim-string-literal production from the C# grammar. See issue 93.
fallthroughStylePatterns.push(
[PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
}
var hc = options['hashComments'];
if (hc) {
if (options['cStyleComments']) {
if (hc > 1) { // multiline hash comments
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
} else {
// Stop C preprocessor declarations at an unclosed open comment
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\r\n]*)/,
null, '#']);
}
// #include <stdio.h>
fallthroughStylePatterns.push(
[PR_STRING,
/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
null]);
} else {
shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
}
}
if (options['cStyleComments']) {
fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
fallthroughStylePatterns.push(
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
}
var regexLiterals = options['regexLiterals'];
if (regexLiterals) {
/**
* @const
*/
var regexExcls = regexLiterals > 1
? '' // Multiline regex literals
: '\n\r';
/**
* @const
*/
var regexAny = regexExcls ? '.' : '[\\S\\s]';
/**
* @const
*/
var REGEX_LITERAL = (
// A regular expression literal starts with a slash that is
// not followed by * or / so that it is not confused with
// comments.
'/(?=[^/*' + regexExcls + '])'
// and then contains any number of raw characters,
+ '(?:[^/\\x5B\\x5C' + regexExcls + ']'
// escape sequences (\x5C),
+ '|\\x5C' + regexAny
// or non-nesting character sets (\x5B\x5D);
+ '|\\x5B(?:[^\\x5C\\x5D' + regexExcls + ']'
+ '|\\x5C' + regexAny + ')*(?:\\x5D|$))+'
// finally closed by a /.
+ '/');
fallthroughStylePatterns.push(
['lang-regex',
RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
]);
}
var types = options['types'];
if (types) {
fallthroughStylePatterns.push([PR_TYPE, types]);
}
var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
if (keywords.length) {
fallthroughStylePatterns.push(
[PR_KEYWORD,
new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
null]);
}
shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']);
var punctuation =
// The Bash man page says
// A word is a sequence of characters considered as a single
// unit by GRUB. Words are separated by metacharacters,
// which are the following plus space, tab, and newline: { }
// | & $ ; < >
// ...
// A word beginning with # causes that word and all remaining
// characters on that line to be ignored.
// which means that only a '#' after /(?:^|[{}|&$;<>\s])/ starts a
// comment but empirically
// $ echo {#}
// {#}
// $ echo \$#
// $#
// $ echo }#
// }#
// so /(?:^|[|&;<>\s])/ is more appropriate.
// http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC3
// suggests that this definition is compatible with a
// default mode that tries to use a single token definition
// to recognize both bash/python style comments and C
// preprocessor directives.
// This definition of punctuation does not include # in the list of
// follow-on exclusions, so # will not be broken before if preceeded
// by a punctuation character. We could try to exclude # after
// [|&;<>] but that doesn't seem to cause many major problems.
// If that does turn out to be a problem, we should change the below
// when hc is truthy to include # in the run of punctuation characters
// only when not followint [|&;<>].
'^.[^\\s\\w.$@\'"`/\\\\]*';
if (options['regexLiterals']) {
punctuation += '(?!\s*\/)';
}
fallthroughStylePatterns.push(
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
[PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null],
[PR_TYPE, /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
[PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null],
[PR_LITERAL,
new RegExp(
'^(?:'
// A hex number
+ '0x[a-f0-9]+'
// or an octal or decimal number,
+ '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
// possibly in scientific notation
+ '(?:e[+\\-]?\\d+)?'
+ ')'
// with an optional modifier like UL for unsigned long
+ '[a-z]*', 'i'),
null, '0123456789'],
// Don't treat escaped quotes in bash as starting strings.
// See issue 144.
[PR_PLAIN, /^\\[\s\S]?/, null],
[PR_PUNCTUATION, new RegExp(punctuation), null]);
return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
}
var decorateSource = sourceDecorator({
'keywords': ALL_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'multiLineStrings': true,
'regexLiterals': true
});
/**
* Given a DOM subtree, wraps it in a list, and puts each line into its own
* list item.
*
* @param {Node} node modified in place. Its content is pulled into an
* HTMLOListElement, and each line is moved into a separate list item.
* This requires cloning elements, so the input might not have unique
* IDs after numbering.
* @param {boolean} isPreformatted true iff white-space in text nodes should
* be treated as significant.
*/
function numberLines(node, opt_startLineNum, isPreformatted) {
var nocode = /(?:^|\s)nocode(?:\s|$)/;
var lineBreak = /\r\n?|\n/;
var document = node.ownerDocument;
var li = document.createElement('li');
while (node.firstChild) {
li.appendChild(node.firstChild);
}
// An array of lines. We split below, so this is initialized to one
// un-split line.
var listItems = [li];
function walk(node) {
var type = node.nodeType;
if (type == 1 && !nocode.test(node.className)) { // Element
if ('br' === node.nodeName) {
breakAfter(node);
// Discard the <BR> since it is now flush against a </LI>.
if (node.parentNode) {
node.parentNode.removeChild(node);
}
} else {
for (var child = node.firstChild; child; child = child.nextSibling) {
walk(child);
}
}
} else if ((type == 3 || type == 4) && isPreformatted) { // Text
var text = node.nodeValue;
var match = text.match(lineBreak);
if (match) {
var firstLine = text.substring(0, match.index);
node.nodeValue = firstLine;
var tail = text.substring(match.index + match[0].length);
if (tail) {
var parent = node.parentNode;
parent.insertBefore(
document.createTextNode(tail), node.nextSibling);
}
breakAfter(node);
if (!firstLine) {
// Don't leave blank text nodes in the DOM.
node.parentNode.removeChild(node);
}
}
}
}
// Split a line after the given node.
function breakAfter(lineEndNode) {
// If there's nothing to the right, then we can skip ending the line
// here, and move root-wards since splitting just before an end-tag
// would require us to create a bunch of empty copies.
while (!lineEndNode.nextSibling) {
lineEndNode = lineEndNode.parentNode;
if (!lineEndNode) { return; }
}
function breakLeftOf(limit, copy) {
// Clone shallowly if this node needs to be on both sides of the break.
var rightSide = copy ? limit.cloneNode(false) : limit;
var parent = limit.parentNode;
if (parent) {
// We clone the parent chain.
// This helps us resurrect important styling elements that cross lines.
// E.g. in <i>Foo<br>Bar</i>
// should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
var parentClone = breakLeftOf(parent, 1);
// Move the clone and everything to the right of the original
// onto the cloned parent.
var next = limit.nextSibling;
parentClone.appendChild(rightSide);
for (var sibling = next; sibling; sibling = next) {
next = sibling.nextSibling;
parentClone.appendChild(sibling);
}
}
return rightSide;
}
var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
// Walk the parent chain until we reach an unattached LI.
for (var parent;
// Check nodeType since IE invents document fragments.
(parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
copiedListItem = parent;
}
// Put it on the list of lines for later processing.
listItems.push(copiedListItem);
}
// Split lines while there are lines left to split.
for (var i = 0; // Number of lines that have been split so far.
i < listItems.length; // length updated by breakAfter calls.
++i) {
walk(listItems[i]);
}
// Make sure numeric indices show correctly.
if (opt_startLineNum === (opt_startLineNum|0)) {
listItems[0].setAttribute('value', opt_startLineNum);
}
var ol = document.createElement('ol');
ol.className = 'linenums';
var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
for (var i = 0, n = listItems.length; i < n; ++i) {
li = listItems[i];
// Stick a class on the LIs so that stylesheets can
// color odd/even rows, or any other row pattern that
// is co-prime with 10.
li.className = 'L' + ((i + offset) % 10);
if (!li.firstChild) {
li.appendChild(document.createTextNode('\xA0'));
}
ol.appendChild(li);
}
node.appendChild(ol);
}
/**
* Breaks {@code job.sourceCode} around style boundaries in
* {@code job.decorations} and modifies {@code job.sourceNode} in place.
* @param {Object} job like <pre>{
* sourceCode: {string} source as plain text,
* sourceNode: {HTMLElement} the element containing the source,
* spans: {Array.<number|Node>} alternating span start indices into source
* and the text node or element (e.g. {@code <BR>}) corresponding to that
* span.
* decorations: {Array.<number|string} an array of style classes preceded
* by the position at which they start in job.sourceCode in order
* }</pre>
* @private
*/
function recombineTagsAndDecorations(job) {
var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent);
isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8;
var newlineRe = /\n/g;
var source = job.sourceCode;
var sourceLength = source.length;
// Index into source after the last code-unit recombined.
var sourceIndex = 0;
var spans = job.spans;
var nSpans = spans.length;
// Index into spans after the last span which ends at or before sourceIndex.
var spanIndex = 0;
var decorations = job.decorations;
var nDecorations = decorations.length;
// Index into decorations after the last decoration which ends at or before
// sourceIndex.
var decorationIndex = 0;
// Remove all zero-length decorations.
decorations[nDecorations] = sourceLength;
var decPos, i;
for (i = decPos = 0; i < nDecorations;) {
if (decorations[i] !== decorations[i + 2]) {
decorations[decPos++] = decorations[i++];
decorations[decPos++] = decorations[i++];
} else {
i += 2;
}
}
nDecorations = decPos;
// Simplify decorations.
for (i = decPos = 0; i < nDecorations;) {
var startPos = decorations[i];
// Conflate all adjacent decorations that use the same style.
var startDec = decorations[i + 1];
var end = i + 2;
while (end + 2 <= nDecorations && decorations[end + 1] === startDec) {
end += 2;
}
decorations[decPos++] = startPos;
decorations[decPos++] = startDec;
i = end;
}
nDecorations = decorations.length = decPos;
var sourceNode = job.sourceNode;
var oldDisplay;
if (sourceNode) {
oldDisplay = sourceNode.style.display;
sourceNode.style.display = 'none';
}
try {
var decoration = null;
while (spanIndex < nSpans) {
var spanStart = spans[spanIndex];
var spanEnd = spans[spanIndex + 2] || sourceLength;
var decEnd = decorations[decorationIndex + 2] || sourceLength;
var end = Math.min(spanEnd, decEnd);
var textNode = spans[spanIndex + 1];
var styledText;
if (textNode.nodeType !== 1 // Don't muck with <BR>s or <LI>s
// Don't introduce spans around empty text nodes.
&& (styledText = source.substring(sourceIndex, end))) {
// This may seem bizarre, and it is. Emitting LF on IE causes the
// code to display with spaces instead of line breaks.
// Emitting Windows standard issue linebreaks (CRLF) causes a blank
// space to appear at the beginning of every line but the first.
// Emitting an old Mac OS 9 line separator makes everything spiffy.
if (isIE8OrEarlier) {
styledText = styledText.replace(newlineRe, '\r');
}
textNode.nodeValue = styledText;
var document = textNode.ownerDocument;
var span = document.createElement('span');
span.className = decorations[decorationIndex + 1];
var parentNode = textNode.parentNode;
parentNode.replaceChild(span, textNode);
span.appendChild(textNode);
if (sourceIndex < spanEnd) { // Split off a text node.
spans[spanIndex + 1] = textNode
// TODO: Possibly optimize by using '' if there's no flicker.
= document.createTextNode(source.substring(end, spanEnd));
parentNode.insertBefore(textNode, span.nextSibling);
}
}
sourceIndex = end;
if (sourceIndex >= spanEnd) {
spanIndex += 2;
}
if (sourceIndex >= decEnd) {
decorationIndex += 2;
}
}
} finally {
if (sourceNode) {
sourceNode.style.display = oldDisplay;
}
}
}
/** Maps language-specific file extensions to handlers. */
var langHandlerRegistry = {};
/** Register a language handler for the given file extensions.
* @param {function (Object)} handler a function from source code to a list
* of decorations. Takes a single argument job which describes the
* state of the computation. The single parameter has the form
* {@code {
* sourceCode: {string} as plain text.
* decorations: {Array.<number|string>} an array of style classes
* preceded by the position at which they start in
* job.sourceCode in order.
* The language handler should assigned this field.
* basePos: {int} the position of source in the larger source chunk.
* All positions in the output decorations array are relative
* to the larger source chunk.
* } }
* @param {Array.<string>} fileExtensions
*/
function registerLangHandler(handler, fileExtensions) {
for (var i = fileExtensions.length; --i >= 0;) {
var ext = fileExtensions[i];
if (!langHandlerRegistry.hasOwnProperty(ext)) {
langHandlerRegistry[ext] = handler;
} else if (win['console']) {
console['warn']('cannot override language handler %s', ext);
}
}
}
function langHandlerForExtension(extension, source) {
if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
// Treat it as markup if the first non whitespace character is a < and
// the last non-whitespace character is a >.
extension = /^\s*</.test(source)
? 'default-markup'
: 'default-code';
}
return langHandlerRegistry[extension];
}
registerLangHandler(decorateSource, ['default-code']);
registerLangHandler(
createSimpleLexer(
[],
[
[PR_PLAIN, /^[^<?]+/],
[PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
[PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/],
// Unescaped content in an unknown language
['lang-', /^<\?([\s\S]+?)(?:\?>|$)/],
['lang-', /^<%([\s\S]+?)(?:%>|$)/],
[PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
// Unescaped content in javascript. (Or possibly vbscript).
['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
// Contains unescaped stylesheet content
['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i]
]),
['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
registerLangHandler(
createSimpleLexer(
[
[PR_PLAIN, /^[\s]+/, null, ' \t\r\n'],
[PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
],
[
[PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
[PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
[PR_PUNCTUATION, /^[=<>\/]+/],
['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i],
['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i],
['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i],
['lang-css', /^style\s*=\s*\"([^\"]+)\"/i],
['lang-css', /^style\s*=\s*\'([^\']+)\'/i],
['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i]
]),
['in.tag']);
registerLangHandler(
createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
registerLangHandler(sourceDecorator({
'keywords': CPP_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'types': C_TYPES
}), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
registerLangHandler(sourceDecorator({
'keywords': 'null,true,false'
}), ['json']);
registerLangHandler(sourceDecorator({
'keywords': CSHARP_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'verbatimStrings': true,
'types': C_TYPES
}), ['cs']);
registerLangHandler(sourceDecorator({
'keywords': JAVA_KEYWORDS,
'cStyleComments': true
}), ['java']);
registerLangHandler(sourceDecorator({
'keywords': SH_KEYWORDS,
'hashComments': true,
'multiLineStrings': true
}), ['bash', 'bsh', 'csh', 'sh']);
registerLangHandler(sourceDecorator({
'keywords': PYTHON_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'tripleQuotedStrings': true
}), ['cv', 'py', 'python']);
registerLangHandler(sourceDecorator({
'keywords': PERL_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'regexLiterals': 2 // multiline regex literals
}), ['perl', 'pl', 'pm']);
registerLangHandler(sourceDecorator({
'keywords': RUBY_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'regexLiterals': true
}), ['rb', 'ruby']);
registerLangHandler(sourceDecorator({
'keywords': JSCRIPT_KEYWORDS,
'cStyleComments': true,
'regexLiterals': true
}), ['javascript', 'js']);
registerLangHandler(sourceDecorator({
'keywords': COFFEE_KEYWORDS,
'hashComments': 3, // ### style block comments
'cStyleComments': true,
'multilineStrings': true,
'tripleQuotedStrings': true,
'regexLiterals': true
}), ['coffee']);
registerLangHandler(sourceDecorator({
'keywords': RUST_KEYWORDS,
'cStyleComments': true,
'multilineStrings': true
}), ['rc', 'rs', 'rust']);
registerLangHandler(
createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
function applyDecorator(job) {
var opt_langExtension = job.langExtension;
try {
// Extract tags, and convert the source code to plain text.
var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre);
/** Plain text. @type {string} */
var source = sourceAndSpans.sourceCode;
job.sourceCode = source;
job.spans = sourceAndSpans.spans;
job.basePos = 0;
// Apply the appropriate language handler
langHandlerForExtension(opt_langExtension, source)(job);
// Integrate the decorations and tags back into the source code,
// modifying the sourceNode in place.
recombineTagsAndDecorations(job);
} catch (e) {
if (win['console']) {
console['log'](e && e['stack'] || e);
}
}
}
/**
* Pretty print a chunk of code.
* @param sourceCodeHtml {string} The HTML to pretty print.
* @param opt_langExtension {string} The language name to use.
* Typically, a filename extension like 'cpp' or 'java'.
* @param opt_numberLines {number|boolean} True to number lines,
* or the 1-indexed number of the first line in sourceCodeHtml.
*/
function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
var container = document.createElement('div');
// This could cause images to load and onload listeners to fire.
// E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
// We assume that the inner HTML is from a trusted source.
// The pre-tag is required for IE8 which strips newlines from innerHTML
// when it is injected into a <pre> tag.
// http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
// http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
container = container.firstChild;
if (opt_numberLines) {
numberLines(container, opt_numberLines, true);
}
var job = {
langExtension: opt_langExtension,
numberLines: opt_numberLines,
sourceNode: container,
pre: 1
};
applyDecorator(job);
return container.innerHTML;
}
/**
* Find all the {@code <pre>} and {@code <code>} tags in the DOM with
* {@code class=prettyprint} and prettify them.
*
* @param {Function} opt_whenDone called when prettifying is done.
* @param {HTMLElement|HTMLDocument} opt_root an element or document
* containing all the elements to pretty print.
* Defaults to {@code document.body}.
*/
function $prettyPrint(opt_whenDone, opt_root) {
var root = opt_root || document.body;
var doc = root.ownerDocument || document;
function byTagName(tn) { return root.getElementsByTagName(tn); }
// fetch a list of nodes to rewrite
var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
var elements = [];
for (var i = 0; i < codeSegments.length; ++i) {
for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
elements.push(codeSegments[i][j]);
}
}
codeSegments = null;
var clock = Date;
if (!clock['now']) {
clock = { 'now': function () { return +(new Date); } };
}
// The loop is broken into a series of continuations to make sure that we
// don't make the browser unresponsive when rewriting a large page.
var k = 0;
var prettyPrintingJob;
var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
var prettyPrintRe = /\bprettyprint\b/;
var prettyPrintedRe = /\bprettyprinted\b/;
var preformattedTagNameRe = /pre|xmp/i;
var codeRe = /^code$/i;
var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
var EMPTY = {};
function doWork() {
var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
clock['now']() + 250 /* ms */ :
Infinity);
for (; k < elements.length && clock['now']() < endTime; k++) {
var cs = elements[k];
// Look for a preceding comment like
// <?prettify lang="..." linenums="..."?>
var attrs = EMPTY;
{
for (var preceder = cs; (preceder = preceder.previousSibling);) {
var nt = preceder.nodeType;
// <?foo?> is parsed by HTML 5 to a comment node (8)
// like <!--?foo?-->, but in XML is a processing instruction
var value = (nt === 7 || nt === 8) && preceder.nodeValue;
if (value
? !/^\??prettify\b/.test(value)
: (nt !== 3 || /\S/.test(preceder.nodeValue))) {
// Skip over white-space text nodes but not others.
break;
}
if (value) {
attrs = {};
value.replace(
/\b(\w+)=([\w:.%+-]+)/g,
function (_, name, value) { attrs[name] = value; });
break;
}
}
}
var className = cs.className;
if ((attrs !== EMPTY || prettyPrintRe.test(className))
// Don't redo this if we've already done it.
// This allows recalling pretty print to just prettyprint elements
// that have been added to the page since last call.
&& !prettyPrintedRe.test(className)) {
// make sure this is not nested in an already prettified element
var nested = false;
for (var p = cs.parentNode; p; p = p.parentNode) {
var tn = p.tagName;
if (preCodeXmpRe.test(tn)
&& p.className && prettyPrintRe.test(p.className)) {
nested = true;
break;
}
}
if (!nested) {
// Mark done. If we fail to prettyprint for whatever reason,
// we shouldn't try again.
cs.className += ' prettyprinted';
// If the classes includes a language extensions, use it.
// Language extensions can be specified like
// <pre class="prettyprint lang-cpp">
// the language extension "cpp" is used to find a language handler
// as passed to PR.registerLangHandler.
// HTML5 recommends that a language be specified using "language-"
// as the prefix instead. Google Code Prettify supports both.
// http://dev.w3.org/html5/spec-author-view/the-code-element.html
var langExtension = attrs['lang'];
if (!langExtension) {
langExtension = className.match(langExtensionRe);
// Support <pre class="prettyprint"><code class="language-c">
var wrapper;
if (!langExtension && (wrapper = childContentWrapper(cs))
&& codeRe.test(wrapper.tagName)) {
langExtension = wrapper.className.match(langExtensionRe);
}
if (langExtension) { langExtension = langExtension[1]; }
}
var preformatted;
if (preformattedTagNameRe.test(cs.tagName)) {
preformatted = 1;
} else {
var currentStyle = cs['currentStyle'];
var defaultView = doc.defaultView;
var whitespace = (
currentStyle
? currentStyle['whiteSpace']
: (defaultView
&& defaultView.getComputedStyle)
? defaultView.getComputedStyle(cs, null)
.getPropertyValue('white-space')
: 0);
preformatted = whitespace
&& 'pre' === whitespace.substring(0, 3);
}
// Look for a class like linenums or linenums:<n> where <n> is the
// 1-indexed number of the first line.
var lineNums = attrs['linenums'];
if (!(lineNums = lineNums === 'true' || +lineNums)) {
lineNums = className.match(/\blinenums\b(?::(\d+))?/);
lineNums =
lineNums
? lineNums[1] && lineNums[1].length
? +lineNums[1] : true
: false;
}
if (lineNums) { numberLines(cs, lineNums, preformatted); }
// do the pretty printing
prettyPrintingJob = {
langExtension: langExtension,
sourceNode: cs,
numberLines: lineNums,
pre: preformatted
};
applyDecorator(prettyPrintingJob);
}
}
}
if (k < elements.length) {
// finish up in a continuation
setTimeout(doWork, 250);
} else if ('function' === typeof opt_whenDone) {
opt_whenDone();
}
}
doWork();
}
/**
* Contains functions for creating and registering new language handlers.
* @type {Object}
*/
var PR = win['PR'] = {
'createSimpleLexer': createSimpleLexer,
'registerLangHandler': registerLangHandler,
'sourceDecorator': sourceDecorator,
'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
'PR_COMMENT': PR_COMMENT,
'PR_DECLARATION': PR_DECLARATION,
'PR_KEYWORD': PR_KEYWORD,
'PR_LITERAL': PR_LITERAL,
'PR_NOCODE': PR_NOCODE,
'PR_PLAIN': PR_PLAIN,
'PR_PUNCTUATION': PR_PUNCTUATION,
'PR_SOURCE': PR_SOURCE,
'PR_STRING': PR_STRING,
'PR_TAG': PR_TAG,
'PR_TYPE': PR_TYPE,
'prettyPrintOne':
IN_GLOBAL_SCOPE
? (win['prettyPrintOne'] = $prettyPrintOne)
: (prettyPrintOne = $prettyPrintOne),
'prettyPrint': prettyPrint =
IN_GLOBAL_SCOPE
? (win['prettyPrint'] = $prettyPrint)
: (prettyPrint = $prettyPrint)
};
// Make PR available via the Asynchronous Module Definition (AMD) API.
// Per https://github.com/amdjs/amdjs-api/wiki/AMD:
// The Asynchronous Module Definition (AMD) API specifies a
// mechanism for defining modules such that the module and its
// dependencies can be asynchronously loaded.
// ...
// To allow a clear indicator that a global define function (as
// needed for script src browser loading) conforms to the AMD API,
// any global define function SHOULD have a property called "amd"
// whose value is an object. This helps avoid conflict with any
// other existing JavaScript code that could have defined a define()
// function that does not conform to the AMD API.
if (typeof define === "function" && define['amd']) {
define("google-code-prettify", [], function () {
return PR;
});
}
})();
define("prettify", function(){});
define('itemView',[
'underscore',
'backbone',
'App',
// Templates
'text!tpl/item.html',
'text!tpl/class.html',
'text!tpl/itemEnd.html',
// Tools
'prettify'
], function (_, Backbone, App, itemTpl, classTpl, endTpl) {
var itemView = Backbone.View.extend({
el: '#item',
init: function () {
this.$html = $('html');
this.$body = $('body');
this.$scrollBody = $('html, body'); // hack for Chrome/Firefox scroll
this.tpl = _.template(itemTpl);
this.classTpl = _.template(classTpl);
this.endTpl = _.template(endTpl);
return this;
},
render: function (item) {
if (item) {
var itemHtml = '',
cleanItem = this.clean(item),
isClass = item.hasOwnProperty('itemtype') ? 0 : 1,
collectionName = isClass ? 'Constructor' : this.capitalizeFirst(cleanItem.itemtype),
isConstructor = cleanItem.is_constructor;
cleanItem.isMethod = collectionName === 'Method';
// create syntax string
var syntax = '';
if (isConstructor) syntax += 'new ';
syntax += cleanItem.name;
if (cleanItem.isMethod || isConstructor) {
syntax += '(';
if (cleanItem.params) {
for (var i=0; i<cleanItem.params.length; i++) {
var p = cleanItem.params[i];
if (p.optional) syntax += '[';
syntax += p.name;
if (p.optdefault) syntax += '='+p.optdefault;
if (p.optional) syntax += ']';
if (i !== cleanItem.params.length-1) {
syntax += ',';
}
}
}
syntax += ')';
}
// Set the item header (title)
// Set item contents
if (isClass) {
if (isConstructor) {
var constructor = this.tpl({
item: cleanItem,
syntax: syntax
});
cleanItem.constructor = constructor;
}
var contents = _.find(App.classes, function(c){ return c.name === cleanItem.name; });
cleanItem.things = contents.items;
itemHtml = this.classTpl(cleanItem);
} else {
itemHtml = this.tpl({
item: cleanItem,
syntax: syntax
});
}
itemHtml += this.endTpl({item:cleanItem});
// Insert the view in the dom
this.$el.html(itemHtml);
renderCode();
Prism.highlightAll();
}
return this;
},
/**
* Clean item properties: url encode properties containing paths.
* @param {object} item The item object.
* @returns {object} Returns the same item object with urlencoded paths.
*/
clean: function (item) {
var cleanItem = item;
if (cleanItem.hasOwnProperty('file')) {
cleanItem.urlencodedfile = encodeURIComponent(item.file);
}
return cleanItem;
},
/**
* Show a single item.
* @param {object} item Item object.
* @returns {object} This view.
*/
show: function (item) {
if (item) {
this.render(item);
}
App.pageView.hideContentViews();
this.$el.show();
this.scrollTop();
//window.scrollTo(0, 0); // LM
return this;
},
/**
* Show a message if no item is found.
* @returns {object} This view.
*/
nothingFound: function () {
this.$el.html("<p><br><br>Ouch. I am unable to find any item that match the current query.</p>");
App.pageView.hideContentViews();
this.$el.show();
return this;
},
/**
* Scroll to the top of the window with an animation.
*/
scrollTop: function() {
// Hack for Chrome/Firefox scroll animation
// Chrome scrolls 'body', Firefox scrolls 'html'
var scroll = this.$body.scrollTop() > 0 || this.$html.scrollTop() > 0;
if (scroll) {
this.$scrollBody.animate({'scrollTop': 0}, 600);
}
},
/**
* Helper method to capitalize the first letter of a string
* @param {string} str
* @returns {string} Returns the string.
*/
capitalizeFirst: function (str) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
});
return itemView;
});
define('text!tpl/menu.html',[],function () { return '\n<% var i=0; %>\n<% var max=Math.floor(groups.length/4); %>\n<% var rem=groups.length%max; %>\n\n<% _.each(groups, function(group){ %>\n <% var m = rem > 0 ? 1 : 0 %>\n <% if (i === 0) { %>\n <dl>\n <% } %>\n <dd><a href="#group-<%=group%>"><%=group%></a></dd>\n <% if (i === (max+m-1)) { %>\n </dl>\n \t<% rem-- %>\n \t<% i=0 %>\n <% } else { %>\n \t<% i++ %>\n <% } %>\n<% }); %>';});
define('menuView',[
'underscore',
'backbone',
'App',
'text!tpl/menu.html'
], function(_, Backbone, App, menuTpl) {
var menuView = Backbone.View.extend({
el: '#collection-list-nav',
/**
* Init.
* @returns {object} This view.
*/
init: function() {
this.menuTpl = _.template(menuTpl);
return this;
},
/**
* Render.
* @returns {object} This view.
*/
render: function() {
var groups = [];
_.each(App.modules, function (item, i) {
if (!item.is_submodule) {
if (!item.file || item.file.indexOf('addons') === -1) { //addons don't get displayed on main page
groups.push(item.name);
}
}
//}
});
// Sort groups by name A-Z
groups.sort();
var menuHtml = this.menuTpl({
'groups': groups
});
// Render the view
this.$el.html(menuHtml);
},
hide: function() {
this.$el.hide();
},
show: function() {
this.$el.show();
},
/**
* Update the menu.
* @param {string} el The name of the current route.
*/
update: function(menuItem) {
//console.log(menuItem);
// this.$menuItems.removeClass('active');
// this.$menuItems.find('a[href=#'+menuItem+']').parent().addClass('active');
}
});
return menuView;
});
define('text!tpl/library.html',[],function () { return '<h3><%= module.name %></h3>\n\n<p><%= module.description %></p>\n\n<div class="reference-group clearfix"> \n\n<% _.each(groups, function(group){ %>\n <dl>\n <% if (group.name !== module.name) { %>\n <dt><a href="<%=group.hash%>" <% if (group.module !== module.name) { %>class="core"<% } %>><h4><%=group.name%>()</h4></a></dt>\n <% } %>\n <p>\n <% _.each(group.items, function(item) { %>\n <dd><a href="<%=item.hash%>" <% if (item.module !== module.name) { %>class="core"<% } %>><%=item.name%><% if (item.itemtype === \'method\') { %>()<%}%></a></dd>\n <% }); %>\n </p>\n </dl>\n<% }); %>\n</div>';});
define('libraryView',[
'underscore',
'backbone',
'App',
// Templates
'text!tpl/library.html'
], function (_, Backbone, App, libraryTpl) {
var libraryView = Backbone.View.extend({
el: '#list',
events: {},
/**
* Init.
*/
init: function () {
this.libraryTpl = _.template(libraryTpl);
return this;
},
/**
* Render the list.
*/
render: function (m, listCollection) {
if (m && listCollection) {
var self = this;
// Render items and group them by module
// module === group
this.groups = {};
_.each(m.items, function (item, i) {
var module = item.module || '_';
var group = item.class || '_';
var hash = App.router.getHash(item);
var ind = hash.lastIndexOf('/');
hash = hash.substring(0, ind);
// Create a group list
if (!self.groups[group]) {
self.groups[group] = {
name: group.replace('_', ' '),
module: module,
hash: hash,
items: []
};
}
self.groups[group].items.push(item);
});
// Sort groups by name A-Z
_.sortBy(self.groups, this.sortByName);
// Put the <li> items html into the list <ul>
var libraryHtml = self.libraryTpl({
'title': self.capitalizeFirst(listCollection),
'module': m.module,
'groups': self.groups
});
// Render the view
this.$el.html(libraryHtml);
}
return this;
},
/**
* Show a list of items.
* @param {array} items Array of item objects.
* @returns {object} This view.
*/
show: function (listGroup) {
if (App[listGroup]) {
this.render(App[listGroup], listGroup);
}
App.pageView.hideContentViews();
this.$el.show();
return this;
},
/**
* Helper method to capitalize the first letter of a string
* @param {string} str
* @returns {string} Returns the string.
*/
capitalizeFirst: function (str) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
},
/**
* Sort function (for the Array.prototype.sort() native method): from A to Z.
* @param {string} a
* @param {string} b
* @returns {Array} Returns an array with elements sorted from A to Z.
*/
sortAZ: function (a, b) {
return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase() ? 1 : -1;
},
sortByName: function (a, b) {
return a.name > b.name ? 1 : -1;
}
});
return libraryView;
});
define('pageView',[
'underscore',
'backbone',
'App',
// Views
'searchView',
'listView',
'itemView',
'menuView',
'libraryView'
], function(_, Backbone, App, searchView, listView, itemView, menuView, libraryView) {
var pageView = Backbone.View.extend({
el: 'body',
/**
* Init.
*/
init: function() {
App.$container = $('#container');
App.contentViews = [];
return this;
},
/**
* Render.
*/
render: function() {
// Menu view
if (!App.menuView) {
App.menuView = new menuView();
App.menuView.init().render();
}
// Item view
if (!App.itemView) {
App.itemView = new itemView();
App.itemView.init().render();
// Add the item view to the views array
App.contentViews.push(App.itemView);
}
// List view
if (!App.listView) {
App.listView = new listView();
App.listView.init().render();
// Add the list view to the views array
App.contentViews.push(App.listView);
}
// Libary view
if (!App.libraryView) {
App.libraryView = new libraryView();
App.libraryView.init().render();
// Add the list view to the views array
App.contentViews.push(App.libraryView);
}
// Search
if (!App.searchView) {
App.searchView = new searchView();
App.searchView.init().render();
}
return this;
},
/**
* Hide item and list views.
* @returns {object} This view.
*/
hideContentViews: function() {
_.each(App.contentViews, function(view, i) {
view.$el.hide();
});
return this;
}
});
return pageView;
});
define('router',[
'underscore',
'backbone',
'App'
], function(_, Backbone, App) {
//
var Router = Backbone.Router.extend({
routes: {
'': 'list',
'p5': 'list',
'p5/': 'list',
'classes': 'list',
'search': 'search',
'libraries/:lib': 'library',
':searchClass(/:searchItem)': 'get'
},
/**
* Whether the json API data was loaded.
*/
_initialized: false,
/**
* Initialize the app: load json API data and create searchable arrays.
*/
init: function(callback) {
var self = this;
require(['pageView'], function(pageView) {
// If already initialized, move away from here!
if (self._initialized) {
if (callback)
callback();
return;
}
// Update initialization state: must be done now to avoid recursive mess
self._initialized = true;
// Render views
if (!App.pageView) {
App.pageView = new pageView();
App.pageView.init().render();
}
// If a callback is set (a route has already been called), run it
// otherwise, show the default list
if (callback)
callback();
else
self.list();
});
},
/**
* Start route. Simply check if initialized.
*/
start: function() {
this.init();
},
/**
* Show item details by searching a class or a class item (method, property or event).
* @param {string} searchClass The class name (mandatory).
* @param {string} searchItem The class item name: can be a method, property or event name.
*/
get: function(searchClass, searchItem) {
// if looking for a library page, redirect
if ((searchClass === 'p5.dom' || searchClass === 'p5.sound')
&& !searchItem) {
window.location.hash = '/libraries/'+searchClass;
return;
}
var self = this;
this.init(function() {
var item = self.getItem(searchClass, searchItem);
App.menuView.hide();
if (item) {
App.itemView.show(item);
} else {
//App.itemView.nothingFound();
self.list();
}
});
},
/**
* Returns one item object by searching a class or a class item (method, property or event).
* @param {string} searchClass The class name (mandatory).
* @param {string} searchItem The class item name: can be a method, property or event name.
* @returns {object} The item found or undefined if nothing was found.
*/
getItem: function(searchClass, searchItem) {
var classes = App.classes,
items = App.allItems,
classesCount = classes.length,
itemsCount = items.length,
className = searchClass ? searchClass.toLowerCase() : undefined,
itemName = searchItem ? searchItem.toLowerCase() : undefined,
found;
// Only search for a class, if itemName is undefined
if (className && !itemName) {
for (var i = 0; i < classesCount; i++) {
if (classes[i].name.toLowerCase() === className) {
found = classes[i];
break;
}
}
// Search for a class item
} else if (className && itemName) {
for (var i = 0; i < itemsCount; i++) {
if ((className == 'p5' || items[i].class.toLowerCase() === className) &&
items[i].name.toLowerCase() === itemName) {
found = items[i];
break;
}
}
}
return found;
},
/**
* List items.
* @param {string} collection The name of the collection to list.
*/
list: function(collection) {
collection = 'allItems';
// Make sure collection is valid
if (App.collections.indexOf(collection) < 0) {
return;
}
this.init(function() {
App.menuView.show(collection);
App.menuView.update(collection);
App.listView.show(collection);
});
},
/**
* Display information for a library.
* @param {string} collection The name of the collection to list.
*/
library: function(collection) {
this.init(function() {
App.menuView.hide();
App.libraryView.show(collection.substring(3)); //remove p5.
});
},
/**
* Close all content views.
*/
search: function() {
this.init(function() {
App.menuView.hide();
App.pageView.hideContentViews();
});
},
/**
* Create an hash/url for the item.
* @param {Object} item A class, method, property or event object.
* @returns {String} The hash string, including the '#'.
*/
getHash: function(item) {
if (!item.hash) {
var hash = '#/';
var isClass = item.hasOwnProperty('classitems');
var c = (item.file.indexOf('objects') === -1 && item.file.indexOf('addons') === -1 ) ? 'p5' : item.class;
// Create hash for links
if (isClass) {
hash += item.name;
} else {
hash += c + '/' + item.name;
}
item.hash = hash;
}
return item.hash;
}
});
// Get the router
App.router = new Router();
// Start history
Backbone.history.start();
return App.router;
});
/**
* Define global App.
*/
var App = window.App || {};
define('App', [],function() {
return App;
});
/**
* Load json API data and start the router.
* @param {module} _
* @param {module} Backbone
* @param {module} App
* @param {module} router
*/
require([
'underscore',
'backbone',
'App'], function(_, Backbone, App) {
// Set collections
App.collections = ['allItems', 'classes', 'events', 'methods', 'properties', 'p5.sound', 'p5.dom'];
// Get json API data
$.getJSON("data.json", function(data) {
App.data = data;
App.classes = [];
App.methods = [];
App.properties = [];
App.events = [];
App.allItems = [];
App.sound = { items: [] };
App.dom = { items: [] };
App.modules = [];
App.project = data.project;
var modules = data.modules;
// Get class items (methods, properties, events)
_.each(modules, function(m, idx, array) {
App.modules.push(m);
if (m.name == "p5.sound") {
App.sound.module = m;
}
else if (m.name == "p5.dom") {
App.dom.module = m;
}
});
var items = data.classitems;
var classes = data.classes;
// Get classes
_.each(classes, function(c, idx, array) {
if (c.is_constructor) {
App.classes.push(c);
}
});
// Get class items (methods, properties, events)
_.each(items, function(el, idx, array) {
if (el.itemtype) {
if (el.itemtype === "method") {
App.methods.push(el);
App.allItems.push(el);
} else if (el.itemtype === "property") {
App.properties.push(el);
App.allItems.push(el);
} else if (el.itemtype === "event") {
App.events.push(el);
App.allItems.push(el);
}
// libraries
if (el.module === "p5.sound") {
App.sound.items.push(el);
}
else if (el.module === "p5.dom" || el.module === 'DOM') {
if (el.class === 'p5') {
el.class = 'p5.dom';
}
App.dom.items.push(el);
}
}
});
_.each(App.classes, function(c, idx) {
c.items = _.filter(App.allItems, function(it){ return it.class === c.name; });
});
require(['router']);
});
});
define("main", function(){});
}());
//# sourceMappingURL=reference.js.map |
ajax/libs/material-ui/4.11.3/Avatar/Avatar.min.js | cdnjs/cdnjs | "use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=exports.styles=void 0;var _extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),_objectWithoutProperties2=_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")),React=_interopRequireWildcard(require("react")),_propTypes=_interopRequireDefault(require("prop-types")),_clsx=_interopRequireDefault(require("clsx")),_utils=require("@material-ui/utils"),_withStyles=_interopRequireDefault(require("../styles/withStyles")),_Person=_interopRequireDefault(require("../internal/svg-icons/Person")),styles=function(e){return{root:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,width:40,height:40,fontFamily:e.typography.fontFamily,fontSize:e.typography.pxToRem(20),lineHeight:1,borderRadius:"50%",overflow:"hidden",userSelect:"none"},colorDefault:{color:e.palette.background.default,backgroundColor:"light"===e.palette.type?e.palette.grey[400]:e.palette.grey[600]},circle:{},circular:{},rounded:{borderRadius:e.shape.borderRadius},square:{borderRadius:0},img:{width:"100%",height:"100%",textAlign:"center",objectFit:"cover",color:"transparent",textIndent:1e4},fallback:{width:"75%",height:"75%"}}};function useLoaded(e){var t=e.src,a=e.srcSet,r=React.useState(!1),e=r[0],i=r[1];return React.useEffect(function(){if(t||a){i(!1);var e=!0,r=new Image;return r.src=t,r.srcSet=a,r.onload=function(){e&&i("loaded")},r.onerror=function(){e&&i("error")},function(){e=!1}}},[t,a]),e}exports.styles=styles;var Avatar=React.forwardRef(function(e,r){var t=e.alt,a=e.children,i=e.classes,s=e.className,l=e.component,o=void 0===l?"div":l,n=e.imgProps,u=e.sizes,c=e.src,p=e.srcSet,d=e.variant,f=void 0===d?"circle":d,_=(0,_objectWithoutProperties2.default)(e,["alt","children","classes","className","component","imgProps","sizes","src","srcSet","variant"]),l=null,d=useLoaded({src:c,srcSet:p}),e=c||p,d=e&&"error"!==d,l=d?React.createElement("img",(0,_extends2.default)({alt:t,src:c,srcSet:p,sizes:u,className:i.img},n)):null!=a?a:e&&t?t[0]:React.createElement(_Person.default,{className:i.fallback});return React.createElement(o,(0,_extends2.default)({className:(0,_clsx.default)(i.root,i.system,i[f],s,!d&&i.colorDefault),ref:r},_),l)});"production"!==process.env.NODE_ENV&&(Avatar.propTypes={alt:_propTypes.default.string,children:_propTypes.default.node,classes:(0,_utils.chainPropTypes)(_propTypes.default.object,function(e){e=e.classes;if(null==e)return null;if(null!=e.circle&&1<e.circle.split(" ").length)throw new Error("Material-UI: The `circle` class was deprecated. Use `circular` instead.");return null}),className:_propTypes.default.string,component:_propTypes.default.elementType,imgProps:_propTypes.default.object,sizes:_propTypes.default.string,src:_propTypes.default.string,srcSet:_propTypes.default.string,variant:(0,_utils.chainPropTypes)(_propTypes.default.oneOf(["circle","circular","rounded","square"]),function(e){if("circle"===e.variant)throw new Error('Material-UI: `variant="circle"` was deprecated. Use `variant="circular"` instead.');return null})});var _default=(0,_withStyles.default)(styles,{name:"MuiAvatar"})(Avatar);exports.default=_default; |
src/components/Footer/Footer.react.js | uday96/chat.susi.ai | import React, { Component } from 'react';
import susi from '../../images/susi-logo.svg';
import './Footer.css';
import { Link } from 'react-router-dom';
class Footer extends Component {
constructor(props) {
super(props);
this.state = {
video: false,
}
}
render() {
// Footer Component
return (
<div className='footer-wrapper'>
<div className='footer'>
<div className='footer-container'>
<Link to='/'>
<img src={susi} alt='SUSI' className='susi-logo' />
</Link>
<ul className='alignLeft'>
<li><Link to='/overview'>Overview</Link></li>
<li><Link to='/blog'>Blog</Link></li>
<li><a href='https://github.com/fossasia?utf8=%E2%9C%93&q=susi'>Code</a></li>
</ul>
<ul className='alignRight'>
<li><Link to='/privacy'>Privacy</Link></li>
<li><Link to='/terms'>Terms</Link></li>
<li><Link to='/contact'>Contact</Link></li>
</ul>
</div>
</div>
</div>
);
}
}
export default Footer;
|
solutions/step8/client/index.js | colmarius/universal-react-workshop-app | import {render} from 'react-dom'
import React from 'react'
import Bootstrap from 'bootstrap/dist/css/bootstrap.css'
import App from "./App.jsx"
import {Provider} from 'react-redux'
import {createStore, applyMiddleware} from 'redux'
import reducers from './reducers'
import thunk from 'redux-thunk'
import {loadData} from './actions'
let store
if (typeof window.__PRELOADED_STATE__ !== 'undefined') {
store = createStore(reducers, window.__PRELOADED_STATE__, applyMiddleware(thunk))
} else {
// ...no preloaded state...dispatch the load action!
store = createStore(reducers, applyMiddleware(thunk))
store.dispatch(loadData())
}
render(<Provider store={store}>
<App />
</Provider>,
document.getElementById("container"))
|
src/components/input/autocomplete-select-ref/index.js | KleeGroup/focus-components | import PropTypes from 'prop-types';
import React from 'react';
import createReactClass from 'create-react-class';
import AutocompleteSelect from '../autocomplete-select/field';
import AutocompleteSelectMultiple from '../autocomplete-select-multiple/field';
import referenceMixin from '../../../common/form/mixin/reference-behaviour';
import storeMixin from '../../../common/mixin/store-behaviour';
import toNormalizedLowerString from '../../../utils/string-normalize';
const displayName = 'AutocompleteReference';
const propTypes = {
referenceName: PropTypes.string.isRequired,
keyName: PropTypes.string,
labelName: PropTypes.string,
multiple: PropTypes.bool
}
const defaultProps = {
keyName: 'key',
labelName: 'label',
multiple: false
}
const AutocompleteReference = createReactClass({
displayName: displayName,
mixins: [referenceMixin, storeMixin],
querySearcher(query) {
const normalizedQuery = toNormalizedLowerString(query);
const { referenceName, labelName, keyName } = this.props;
//We use this normalizedList in order not to normalize the list for every query
if (!this.normalizedList && this.state.reference[referenceName]) {
this.normalizedList = this.state.reference[referenceName].map(x => ({ [keyName]: x[keyName], [labelName]: toNormalizedLowerString(x[labelName]) }));
}
let data = (this.normalizedList || []).filter(x => x[labelName].indexOf(normalizedQuery) !== -1);
const totalCount = data.length;
// Let's take only the first 100 propositions
data = data.slice(0, 100)
.map(elt => (this.state.reference[referenceName] || []).find(item => item[keyName] === elt[keyName]));
return Promise.resolve({ data, totalCount })
},
componentWillReceiveProps({ referenceName, labelName }) {
if (referenceName !== this.props.referenceName || labelName !== this.props.labelName) {
this.normalizedList = null;
}
},
keyResolver(key) {
const data = (this.state.reference[this.props.referenceName] || []).find(x => x[this.props.keyName] === key);
return Promise.resolve((data || {})[this.props.labelName] || key)
},
getValue() {
return this.refs.input.getValue();
},
_validate() {
return this.refs.input._validate();
},
render() {
const ToRenderComp = this.props.multiple ? AutocompleteSelectMultiple : AutocompleteSelect;
const hasListLoaded = this.state.reference[this.props.referenceName] && this.state.reference[this.props.referenceName].length > 0;
// We must not render the component with value before the reference list is loaded
const value = hasListLoaded ? this.props.value : this.props.multiple ? [] : '';
return (
<ToRenderComp
ref='input'
{...this.props}
value={value}
querySearcher={this.querySearcher}
keyResolver={this.keyResolver}
keyName={this.props.keyName}
labelName={this.props.labelName}
/>
)
}
})
class AutocompleteReferenceWithProps extends React.Component {
static displayName = 'AutocompleteReferenceWrapped';
static propTypes = propTypes;
static defaultProps = defaultProps;
render() {
return <AutocompleteReference {...this.props} referenceNames={[this.props.referenceName]} />;
}
}
export default AutocompleteReferenceWithProps; |
ajax/libs/rxjs/2.2.7/rx.compat.js | owcc/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
(function (window, undefined) {
var freeExports = typeof exports == 'object' && exports,
freeModule = typeof module == 'object' && module && module.exports == freeExports && module,
freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal) {
window = freeGlobal;
}
/**
* @name Rx
* @type Object
*/
var Rx = { Internals: {} };
// Defaults
function noop() { }
function identity(x) { return x; }
var defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }());
function defaultComparer(x, y) { return isEqual(x, y); }
function defaultSubComparer(x, y) { return x - y; }
function defaultKeySerializer(x) { return x.toString(); }
function defaultError(err) { throw err; }
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() {
if (this.isDisposed) {
throw new Error(objectDisposed);
}
}
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function';
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.Internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
var result;
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a &&
!(a && objectTypes[type]) &&
!(b && objectTypes[otherType])) {
return false;
}
// exit early for `null` and `undefined`, avoiding ES3's Function#call behavior
// http://es5.github.io/#x15.3.4.4
if (a == null || b == null) {
return a === b;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!suportNodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !supportsArgsClass && isArguments(a) ? Object : a.constructor,
ctorB = !supportsArgsClass && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB && !(
isFunction(ctorA) && ctorA instanceof ctorA &&
isFunction(ctorB) && ctorB instanceof ctorB
)) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
length = a.length;
size = b.length;
// compare lengths to determine if a deep comparison is necessary
result = size == a.length;
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
return result;
}
// deep compare each object
for(var key in b) {
if (hasOwnProperty.call(b, key)) {
// count properties and deep compare each property value
size++;
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], b[key], stackA, stackB));
}
}
if (result) {
// ensure both objects have the same number of properties
for (var key in a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.Internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.Internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Utilities
if (!Function.prototype.bind) {
Function.prototype.bind = function (that) {
var target = this,
args = slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
function F() { }
F.prototype = target.prototype;
var self = new F();
var result = target.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
return bound;
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = Object(this),
self = splitString && {}.toString.call(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if ({}.toString.call(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = Object(this),
self = splitString && {}.toString.call(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if ({}.toString.call(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, object);
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) == '[object Array]';
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n != Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.Internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
*/
CompositeDisposablePrototype.clear = function () {
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
};
/**
* Determines whether the CompositeDisposable contains a specific disposable.
* @param {Mixed} item Disposable to search for.
* @returns {Boolean} true if the disposable was found; otherwise, false.
*/
CompositeDisposablePrototype.contains = function (item) {
return this.disposables.indexOf(item) !== -1;
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Represents a disposable resource 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.
*
* @constructor
*/
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
this.isDisposed = false;
this.current = null;
};
var SingleAssignmentDisposablePrototype = SingleAssignmentDisposable.prototype;
/**
* Gets the underlying disposable. After disposal, the result of getting this method is undefined.
* @returns {Disposable} The underlying disposable.
*/
SingleAssignmentDisposablePrototype.getDisposable = function () {
return this.current;
};
/* @private */
SingleAssignmentDisposable.disposable = function (value) {
return arguments.length ? this.getDisposable() : this.setDisposable(value);
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
SingleAssignmentDisposablePrototype.setDisposable = function (value) {
if (this.current) {
throw new Error('Disposable has already been assigned');
}
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
this.current = value;
}
if (shouldDispose && value) {
value.dispose();
}
};
/**
* Disposes the underlying disposable.
*/
SingleAssignmentDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
/**
* Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
* @constructor
*/
var SerialDisposable = Rx.SerialDisposable = function () {
this.isDisposed = false;
this.current = null;
};
var serialDisposablePrototype = SerialDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
serialDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
serialDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
if (old) {
old.dispose();
}
if (shouldDispose && value) {
value.dispose();
}
};
/* @private */
serialDisposablePrototype.disposable = function (value) {
if (!value) {
return this.getDisposable();
} else {
this.setDisposable(value);
}
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
serialDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
/**
* @constructor
* @private
*/
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler, this.disposable = disposable, this.isDisposed = false;
}
/**
* @private
* @memberOf ScheduledDisposable#
*/
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 = window.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
window.clearInterval(id);
});
};
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () {
self(_action);
});
});
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, function (s, p) {
return invokeRecImmediate(s, p);
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
if (timeSpan < 0) {
timeSpan = 0;
}
return timeSpan;
};
return Scheduler;
}());
var SchedulePeriodicRecursive = Rx.Internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var schedulerNoBlockError = 'Scheduler is not allowed to block the thread';
/**
* 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) {
if (dueTime > 0) throw new Error(schedulerNoBlockError);
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 Trampoline() {
queue = new PriorityQueue(4);
}
Trampoline.prototype.dispose = function () {
queue = null;
};
Trampoline.prototype.run = function () {
var item;
while (queue.length > 0) {
item = queue.dequeue();
if (!item.isCancelled()) {
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
};
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt),
t;
if (!queue) {
t = new Trampoline();
try {
queue.enqueue(si);
t.run();
} catch (e) {
throw e;
} finally {
t.dispose();
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return queue === null; };
currentScheduler.ensureTrampoline = function (action) {
if (queue === null) {
return this.schedule(action);
} else {
return action();
}
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
(function () {
function postMessageSupported () {
// Ensure not in a worker
if (!window.postMessage || window.importScripts) { return false; }
var isAsync = false,
oldHandler = window.onmessage;
// Test for async
window.onmessage = function () { isAsync = true; };
window.postMessage('','*');
window.onmessage = oldHandler;
return isAsync;
}
// Check for setImmediate first for Node v0.11+
if (typeof window.setImmediate === 'function') {
scheduleMethod = window.setImmediate;
clearMethod = clearImmediate;
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (window.addEventListener) {
window.addEventListener('message', onGlobalPostMessage, false);
} else {
window.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
window.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!window.MessageChannel) {
var channel = new window.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in window && 'onreadystatechange' in window.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = window.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
window.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return window.setTimeout(action, 0); };
clearMethod = window.clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = window.setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
window.clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/** @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;
}
var NotificationPrototype = Notification.prototype;
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) {
if (arguments.length === 1 && typeof observerOrOnNext === 'object') {
return this._acceptObservable(observerOrOnNext);
}
return this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notification
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
NotificationPrototype.toObservable = function (scheduler) {
var notification = this;
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
if (notification.kind === 'N') {
observer.onCompleted();
}
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) {
return onNext(this.value);
}
function _acceptObservable(observer) {
return observer.onNext(this.value);
}
function toString () {
return 'OnNext(' + this.value + ')';
}
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) {
return onError(this.exception);
}
function _acceptObservable(observer) {
return observer.onError(this.exception);
}
function toString () {
return 'OnError(' + this.exception + ')';
}
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) {
return onCompleted();
}
function _acceptObservable(observer) {
return observer.onCompleted();
}
function toString () {
return 'OnCompleted()';
}
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* @constructor
* @private
*/
var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent, dispose) {
this.moveNext = moveNext;
this.getCurrent = getCurrent;
this.dispose = dispose;
};
/**
* @static
* @memberOf Enumerator
* @private
*/
var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) {
var done = false;
dispose || (dispose = noop);
return new Enumerator(function () {
if (done) {
return false;
}
var result = moveNext();
if (!result) {
done = true;
dispose();
}
return result;
}, function () { return getCurrent(); }, function () {
if (!done) {
dispose();
done = true;
}
});
};
/** @private */
var Enumerable = Rx.Internals.Enumerable = (function () {
/**
* @constructor
* @private
*/
function Enumerable(getEnumerator) {
this.getEnumerator = getEnumerator;
}
/**
* @private
* @memberOf Enumerable#
*/
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e = sources.getEnumerator(), isDisposed = false, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, ex, hasNext = false;
if (!isDisposed) {
try {
hasNext = e.moveNext();
if (hasNext) {
current = e.getCurrent();
} else {
e.dispose();
}
} catch (exception) {
ex = exception;
e.dispose();
}
} else {
return;
}
if (ex) {
observer.onError(ex);
return;
}
if (!hasNext) {
observer.onCompleted();
return;
}
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
e.dispose();
}));
});
};
/**
* @private
* @memberOf Enumerable#
*/
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e = sources.getEnumerator(), isDisposed = false, lastException;
var subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, ex, hasNext;
hasNext = false;
if (!isDisposed) {
try {
hasNext = e.moveNext();
if (hasNext) {
current = e.getCurrent();
}
} catch (exception) {
ex = exception;
}
} else {
return;
}
if (ex) {
observer.onError(ex);
return;
}
if (!hasNext) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
return Enumerable;
}());
/**
* @static
* @private
* @memberOf Enumerable
*/
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount === undefined) {
repeatCount = -1;
}
return new Enumerable(function () {
var current, left = repeatCount;
return enumeratorCreate(function () {
if (left === 0) {
return false;
}
if (left > 0) {
left--;
}
current = value;
return true;
}, function () { return current; });
});
};
/**
* @static
* @private
* @memberOf Enumerable
*/
var enumerableFor = Enumerable.forEach = function (source, selector) {
selector || (selector = identity);
return new Enumerable(function () {
var current, index = -1;
return enumeratorCreate(
function () {
if (++index < source.length) {
current = selector(source[index], index);
return true;
}
return false;
},
function () { return current; }
);
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* 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.
*
* @constructor
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
*
* @memberOf AnonymousObserver
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
*
* @memberOf AnonymousObserver
* @param {Any{ error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*
* @memberOf AnonymousObserver
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var 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));
/** @private */
var ScheduledObserver = Rx.Internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
/** @private */
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
/** @private */
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
/** @private */
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
/** @private */
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
/** @private */
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/** @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 () {
/**
* @constructor
* @private
*/
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
observableProto.finalValue = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var hasValue = false, value;
return source.subscribe(function (x) {
hasValue = true;
value = x;
}, observer.onError.bind(observer), function () {
if (!hasValue) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
};
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber;
if (typeof observerOrOnNext === 'object') {
subscriber = observerOrOnNext;
} else {
subscriber = observerCreate(observerOrOnNext, onError, onCompleted);
}
return this._subscribe(subscriber);
};
/**
* Creates a list from an observable sequence.
*
* @memberOf Observable
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
function accumulator(list, i) {
var newList = list.slice(0);
newList.push(i);
return newList;
}
return this.scan([], accumulator).startWith([]).finalValue();
};
return Observable;
})();
/**
* 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;
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0;
return scheduler.scheduleRecursive(function (self) {
if (count < array.length) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
if (repeatCount == null) {
repeatCount = -1;
}
return observableReturn(value, scheduler).repeat(repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* var res = Rx.Observable.throwException(new Error('Error'));
* var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout);
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* 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 that reacts first.
* @param {Observable} rightSource Second observable sequence.
* @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();
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 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;
}
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
if (typeof handlerOrSecond === 'function') {
return observableCatchHandler(this, handlerOrSecond);
}
return observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(args[i].subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') {
return observableMerge(this, maxConcurrentOrOther);
}
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0,
group = new CompositeDisposable(),
isStopped = false,
q = [],
subscribe = function (xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
var s;
group.remove(subscription);
if (q.length > 0) {
s = q.shift();
subscribe(s);
} else {
activeCount--;
if (isStopped && activeCount === 0) {
observer.onCompleted();
}
}
}));
};
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
if (activeCount === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) {
observer.onCompleted();
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* 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++];
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} other The observable sequence that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
if (isOpen) {
observer.onNext(left);
}
}, observer.onError.bind(observer), function () {
if (isOpen) {
observer.onCompleted();
}
}));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
var next = function (i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = slice.call(arguments);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* 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 (arguments.length === 1) {
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.doAction(observer);
* var res = observable.doAction(onNext);
* var res = observable.doAction(onNext, onError);
* var res = observable.doAction(onNext, onError, onCompleted);
* @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (exception) {
if (!onError) {
observer.onError(exception);
} else {
try {
onError(exception);
} catch (e) {
observer.onError(e);
}
observer.onError(exception);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = source.subscribe(observer);
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(42);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue.
*
* @example
* var res = source.takeLast(5);
* var res = source.takeLast(5, Rx.Scheduler.timeout);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count, scheduler) {
return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); });
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
q.shift();
}
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into 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;
});
};
/**
* 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();
});
});
};
/**
* 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 (x) { return x.toString(); });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, keySerializer) {
var source = this;
keySelector || (keySelector = identity);
keySerializer || (keySerializer = defaultKeySerializer);
return new AnonymousObservable(function (observer) {
var hashSet = {};
return source.subscribe(function (x) {
var key, serializedKey, otherKey, hasMatch = false;
try {
key = keySelector(x);
serializedKey = keySerializer(key);
} catch (exception) {
observer.onError(exception);
return;
}
for (otherKey in hashSet) {
if (serializedKey === otherKey) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
hashSet[serializedKey] = null;
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* 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} [keySerializer] Used to serialize the given object into a string for object comparison.
* @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, keySerializer) {
return this.groupByUntil(keySelector, elementSelector, function () {
return observableNever();
}, keySerializer);
};
/**
* 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} [keySerializer] Used to serialize the given object into a string for object comparison.
* @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, keySerializer) {
var source = this;
elementSelector || (elementSelector = identity);
keySerializer || (keySerializer = defaultKeySerializer);
return new AnonymousObservable(function (observer) {
var map = {},
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w;
try {
key = keySelector(x);
serializedKey = keySerializer(key);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
fireNewMapEntry = false;
try {
writer = map[serializedKey];
if (!writer) {
writer = new Subject();
map[serializedKey] = writer;
fireNewMapEntry = true;
}
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
if (fireNewMapEntry) {
group = new GroupedObservable(key, writer, refCountDisposable);
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
observer.onNext(group);
md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
if (serializedKey in map) {
delete map[serializedKey];
writer.onCompleted();
}
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(noop, function (exn) {
for (w in map) {
map[w].onError(exn);
}
observer.onError(exn);
}, function () {
expire();
}));
}
try {
element = elementSelector(x);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
for (var w in map) {
map[w].onError(ex);
}
observer.onError(ex);
}, function () {
for (var w in map) {
map[w].onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* 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]; });
};
function selectMany(selector) {
return this.select(selector).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.selectMany(function (x) {
return selector(x).select(function (y) {
return resultSelector(x, y);
});
});
}
if (typeof selector === 'function') {
return selectMany.call(this, selector);
}
return selectMany.call(this, function () {
return selector;
});
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* var res = source.takeWhile(function (value) { return value < 10; });
* var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) {
inherits(AnonymousObservable, _super);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (typeof subscriber === 'undefined') {
subscriber = disposableEmpty;
} else if (typeof subscriber === 'function') {
subscriber = disposableCreate(subscriber);
}
return subscriber;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
});
} else {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
}
return autoDetachObserver;
}
_super.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var GroupedObservable = (function (_super) {
inherits(GroupedObservable, _super);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
/**
* @constructor
* @private
*/
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));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
var hv = this.hasValue;
var v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, _super);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.value = null,
this.hasValue = false,
this.observers = [],
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
var v = this.value;
var hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
this.hasValue = true;
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
/** @private */
var AnonymousSubject = (function (_super) {
inherits(AnonymousSubject, _super);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
/**
* @private
* @constructor
*/
function AnonymousSubject(observer, observable) {
_super.call(this, subscribe);
this.observer = observer;
this.observable = observable;
}
addProperties(AnonymousSubject.prototype, Observer, {
/**
* @private
* @memberOf AnonymousSubject#
*/
onCompleted: function () {
this.observer.onCompleted();
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onError: function (exception) {
this.observer.onError(exception);
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
// Check for AMD
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
window.Rx = Rx;
return define(function () {
return Rx;
});
} else if (freeExports) {
if (typeof module == 'object' && module && module.exports == freeExports) {
module.exports = Rx;
} else {
freeExports = Rx;
}
} else {
window.Rx = Rx;
}
}(this)); |
analysis/demonhunterhavoc/src/modules/talents/DemonBlades.js | anom0ly/WoWAnalyzer | import { t } from '@lingui/macro';
import { formatThousands, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import TalentStatisticBox from 'parser/ui/TalentStatisticBox';
import React from 'react';
/**
* Example Report: https://www.warcraftlogs.com/reports/4GR2pwAYW8KtgFJn/#fight=6&source=18
*/
class DemonBlades extends Analyzer {
get furyPerMin() {
return ((this.furyGain - this.furyWaste) / (this.owner.fightDuration / 60000)).toFixed(2);
}
get suggestionThresholds() {
return {
actual: this.furyWaste / this.furyGain,
isGreaterThan: {
minor: 0.03,
average: 0.07,
major: 0.1,
},
style: 'percentage',
};
}
furyGain = 0;
furyWaste = 0;
damage = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.DEMON_BLADES_TALENT.id);
if (!this.active) {
return;
}
this.addEventListener(
Events.energize.by(SELECTED_PLAYER).spell(SPELLS.DEMON_BLADES_FURY),
this.onEnergizeEvent,
);
this.addEventListener(
Events.damage.by(SELECTED_PLAYER).spell(SPELLS.DEMON_BLADES_FURY),
this.onDamageEvent,
);
}
onEnergizeEvent(event) {
this.furyGain += event.resourceChange;
this.furyWaste += event.waste;
}
onDamageEvent(event) {
this.damage += event.amount;
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) =>
suggest(
<>
{' '}
Be mindful of your Fury levels and spend it before capping your Fury due to{' '}
<SpellLink id={SPELLS.DEMON_BLADES_TALENT.id} />.
</>,
)
.icon(SPELLS.DEMON_BLADES_TALENT.icon)
.actual(
t({
id: 'demonhunter.havoc.suggestions.demonBlades.furyWasted',
message: `${formatPercentage(actual)}% Fury wasted`,
}),
)
.recommended(`${formatPercentage(recommended)}% is recommended.`),
);
}
statistic() {
const effectiveFuryGain = this.furyGain - this.furyWaste;
return (
<TalentStatisticBox
talent={SPELLS.DEMON_BLADES_TALENT.id}
position={STATISTIC_ORDER.OPTIONAL(6)}
value={
<>
{this.furyPerMin} <small>Fury per min</small> <br />
{this.owner.formatItemDamageDone(this.damage)}
</>
}
tooltip={
<>
{formatThousands(this.damage)} Total damage
<br />
{effectiveFuryGain} Effective Fury gained
<br />
{this.furyGain} Total Fury gained
<br />
{this.furyWaste} Fury wasted
</>
}
/>
);
}
}
export default DemonBlades;
|
src/components/menu/menu-list.js | bokuweb/re-bulma | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from '../../../build/styles';
import { getCallbacks } from '../../helper/helper';
export default class MenuList extends Component {
static propTypes = {
style: PropTypes.object,
children: PropTypes.any,
className: PropTypes.string,
};
static defaultProps = {
style: {},
className: '',
};
createClassName() {
return [
styles.menuList,
this.props.className,
].join(' ').trim();
}
render() {
return (
<ul
{...getCallbacks(this.props)}
style={this.props.style}
className={this.createClassName()}
>
{this.props.children}
</ul>
);
}
}
|
src/svg-icons/action/redeem.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionRedeem = (props) => (
<SvgIcon {...props}>
<path d="M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm11 15H4v-2h16v2zm0-5H4V8h5.08L7 10.83 8.62 12 11 8.76l1-1.36 1 1.36L15.38 12 17 10.83 14.92 8H20v6z"/>
</SvgIcon>
);
ActionRedeem = pure(ActionRedeem);
ActionRedeem.displayName = 'ActionRedeem';
ActionRedeem.muiName = 'SvgIcon';
export default ActionRedeem;
|
tests/components/Header/Header.spec.js | Dylan1312/pool-elo | import React from 'react'
import { Header } from 'components/Header/Header'
import { IndexLink, Link } from 'react-router'
import { shallow } from 'enzyme'
describe('(Component) Header', () => {
let _wrapper
beforeEach(() => {
_wrapper = shallow(<Header />)
})
it('Renders a welcome message', () => {
const welcome = _wrapper.find('h1')
expect(welcome).to.exist
expect(welcome.text()).to.match(/React Redux Starter Kit/)
})
describe('Navigation links...', () => {
it('Should render a Link to Home route', () => {
expect(_wrapper.contains(
<IndexLink activeClassName='route--active' to='/'>
Home
</IndexLink>
)).to.be.true
})
it('Should render a Link to Counter route', () => {
expect(_wrapper.contains(
<Link activeClassName='route--active' to='/counter'>
Counter
</Link>
)).to.be.true
})
})
})
|
doc/asset/js/jquery.min.js | chinakids/echarts | /*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.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);
|
src/components/ColumnName.js | kkanzelmeyer/project-dashboard | import React, { PropTypes } from 'react';
class ColumnName extends React.Component {
static propTypes = {
name: PropTypes.string,
active: PropTypes.bool
}
render () {
const { name, active } = this.props;
const styles = {
base: {
height: '100%',
width: '100%',
paddingTop: '15px'
},
active: {
fontWeight: 'bold'
}
};
return (
<div style={[styles.base, active && styles.active]}>
{name}
</div>
);
}
}
export default ColumnName;
|
node_modules/react-icons/ti/social-skype.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const TiSocialSkype = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m34.4 22.2c0.1-0.7 0.2-1.4 0.2-2.1 0-4.1-1.4-7.6-4.2-10.4-2.8-2.9-6.3-4.4-10.2-4.4-0.5 0-1 0-1.4 0.1-1.2-0.6-2.6-0.9-4-0.9-2.7 0-5.1 1-7 2.9-1.8 1.9-2.8 4.3-2.8 7 0 1.4 0.3 2.7 0.8 3.9-0.1 0.6-0.1 1.2-0.1 1.8 0 4.1 1.4 7.6 4.2 10.4 2.8 2.9 6.3 4.4 10.3 4.4 0.4 0 0.9 0 1.4-0.1 1.2 0.5 2.4 0.7 3.6 0.7 2.7 0 5.1-1 7-3 1.8-1.9 2.8-4.3 2.8-7 0-1.1-0.2-2.2-0.6-3.3z m-8.6 3.4c-0.4 0.7-1.2 1.3-2.2 1.8-1 0.4-2.2 0.6-3.5 0.6-1.6 0-2.9-0.3-4-0.9-0.8-0.4-1.4-1-1.8-1.7-0.5-0.7-0.7-1.4-0.7-2.1 0-0.4 0.1-0.7 0.4-1 0.3-0.3 0.7-0.5 1.2-0.5 0.3 0 0.7 0.1 1 0.4 0.3 0.3 0.5 0.6 0.6 1 0 0 0.3 0.4 0.7 1.2 0.1 0.2 0.4 0.4 0.9 0.7 0.4 0.2 0.9 0.3 1.6 0.3 0.9 0 1.7-0.2 2.3-0.6 0.5-0.4 0.8-0.9 0.8-1.5 0-0.4-0.2-0.8-0.5-1-0.3-0.3-0.7-0.6-1.1-0.7-0.2-0.1-0.3-0.1-0.6-0.2-0.2 0-0.4-0.1-0.7-0.2-0.3 0-0.6-0.1-0.8-0.1-1.1-0.3-2.1-0.6-2.9-0.9-0.7-0.3-1.4-0.8-1.9-1.5-0.5-0.6-0.7-1.4-0.7-2.3 0-0.8 0.2-1.6 0.7-2.3 0.5-0.7 1.3-1.2 2.2-1.5 1-0.4 2-0.6 3.3-0.6 0.9 0 1.7 0.2 2.5 0.4 0.8 0.3 1.4 0.6 1.9 1 0.5 0.4 0.8 0.8 1.1 1.2 0.2 0.5 0.3 1 0.3 1.3 0 0.4-0.1 0.8-0.4 1.1-0.4 0.3-0.7 0.5-1.2 0.5-0.4 0-0.7-0.1-1-0.3-0.1-0.2-0.3-0.5-0.6-0.9-0.2-0.5-0.5-0.9-1-1.3-0.4-0.3-1-0.4-1.9-0.4-0.8 0-1.4 0.1-1.9 0.5-0.5 0.3-0.7 0.6-0.7 1 0 0.3 0.1 0.5 0.3 0.7 0.1 0.2 0.4 0.4 0.6 0.6 0.2 0.1 0.5 0.2 0.9 0.3 0.1 0.1 0.3 0.1 0.7 0.2 0.3 0.1 0.6 0.1 0.9 0.2 0.4 0.1 1.2 0.3 2.4 0.6 0.7 0.3 1.3 0.6 1.9 0.9 0.6 0.4 1 0.9 1.3 1.4 0.3 0.6 0.4 1.3 0.4 2 0 1-0.3 1.8-0.8 2.6z"/></g>
</Icon>
)
export default TiSocialSkype
|
wp-includes/js/jquery/jquery.js | Ndrubey/RancorWebsite | /*! 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});
jQuery.noConflict();
|
packages/react-jsx-highcharts/src/components/AreaSeries/AreaSeries.js | AlexMayants/react-jsx-highcharts | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Series from '../Series';
class AreaSeries extends Component {
static propTypes = {
id: PropTypes.string.isRequired
};
render () {
return (
<Series {...this.props} type="area" />
);
}
}
export default AreaSeries;
|
ajax/libs/rxjs/2.4.9/rx.lite.extras.js | tmorin/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (factory) {
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;
}
// Because of build optimizers
if (typeof define === 'function' && define.amd) {
define(['rx-lite'], function (Rx, exports) {
return factory(root, exports, Rx);
});
} else if (typeof module === 'object' && module && module.exports === freeExports) {
module.exports = factory(root, module.exports, require('rx-lite'));
} else {
root.Rx = factory(root, {}, root.Rx);
}
}.call(this, function (root, exp, Rx, undefined) {
// References
var Observable = Rx.Observable,
observableProto = Observable.prototype,
observableNever = Observable.never,
observableThrow = Observable.throwException,
AnonymousObservable = Rx.AnonymousObservable,
AnonymousObserver = Rx.AnonymousObserver,
notificationCreateOnNext = Rx.Notification.createOnNext,
notificationCreateOnError = Rx.Notification.createOnError,
notificationCreateOnCompleted = Rx.Notification.createOnCompleted,
Observer = Rx.Observer,
Subject = Rx.Subject,
internals = Rx.internals,
helpers = Rx.helpers,
ScheduledObserver = internals.ScheduledObserver,
SerialDisposable = Rx.SerialDisposable,
SingleAssignmentDisposable = Rx.SingleAssignmentDisposable,
CompositeDisposable = Rx.CompositeDisposable,
RefCountDisposable = Rx.RefCountDisposable,
disposableEmpty = Rx.Disposable.empty,
immediateScheduler = Rx.Scheduler.immediate,
defaultKeySerializer = helpers.defaultKeySerializer,
addRef = Rx.internals.addRef,
identity = helpers.identity,
isPromise = helpers.isPromise,
inherits = internals.inherits,
bindCallback = internals.bindCallback,
noop = helpers.noop,
isScheduler = helpers.isScheduler,
observableFromPromise = Observable.fromPromise,
ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError;
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 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 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);
/**
* 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); };
/**
* 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);
};
/**
* Creates an observer from a notification callback.
* @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) {
var handlerFunc = bindCallback(handler, thisArg, 1);
return new AnonymousObserver(function (x) {
return handlerFunc(notificationCreateOnNext(x));
}, function (e) {
return handlerFunc(notificationCreateOnError(e));
}, function () {
return handlerFunc(notificationCreateOnCompleted());
});
};
/**
* 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 () {
var source = this;
return new AnonymousObserver(
function (x) { source.onNext(x); },
function (e) { source.onError(e); },
function () { source.onCompleted(); }
);
};
/**
* 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);
};
/**
* 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();
}
});
});
};
/**
* 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;
};
/**
* 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);
});
};
/**
* 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;
});
};
/**
* 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);
};
/**
* 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);
};
/**
* 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);
};
return Rx;
}));
|
ajax/libs/react-virtualized/9.0.0-rc.1/react-virtualized.min.js | him2him2/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("React"),require("ReactDOM")):"function"==typeof define&&define.amd?define(["React","ReactDOM"],t):"object"==typeof exports?exports.ReactVirtualized=t(require("React"),require("ReactDOM")):e.ReactVirtualized=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(o){if(n[o])return n[o].exports;var i=n[o]={exports:{},id:o,loaded:!1};return e[o].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=n(1);Object.defineProperty(t,"ArrowKeyStepper",{enumerable:!0,get:function(){return o.ArrowKeyStepper}});var i=n(90);Object.defineProperty(t,"AutoSizer",{enumerable:!0,get:function(){return i.AutoSizer}});var r=n(93);Object.defineProperty(t,"CellMeasurer",{enumerable:!0,get:function(){return r.CellMeasurer}}),Object.defineProperty(t,"CellMeasurerCache",{enumerable:!0,get:function(){return r.CellMeasurerCache}});var l=n(98);Object.defineProperty(t,"Collection",{enumerable:!0,get:function(){return l.Collection}});var a=n(118);Object.defineProperty(t,"ColumnSizer",{enumerable:!0,get:function(){return a.ColumnSizer}});var s=n(120);Object.defineProperty(t,"defaultTableCellDataGetter",{enumerable:!0,get:function(){return s.defaultCellDataGetter}}),Object.defineProperty(t,"defaultTableCellRenderer",{enumerable:!0,get:function(){return s.defaultCellRenderer}}),Object.defineProperty(t,"defaultTableHeaderRenderer",{enumerable:!0,get:function(){return s.defaultHeaderRenderer}}),Object.defineProperty(t,"defaultTableRowRenderer",{enumerable:!0,get:function(){return s.defaultRowRenderer}}),Object.defineProperty(t,"Table",{enumerable:!0,get:function(){return s.Table}}),Object.defineProperty(t,"Column",{enumerable:!0,get:function(){return s.Column}}),Object.defineProperty(t,"SortDirection",{enumerable:!0,get:function(){return s.SortDirection}}),Object.defineProperty(t,"SortIndicator",{enumerable:!0,get:function(){return s.SortIndicator}});var u=n(128);Object.defineProperty(t,"defaultCellRangeRenderer",{enumerable:!0,get:function(){return u.defaultCellRangeRenderer}}),Object.defineProperty(t,"Grid",{enumerable:!0,get:function(){return u.Grid}});var c=n(137);Object.defineProperty(t,"InfiniteLoader",{enumerable:!0,get:function(){return c.InfiniteLoader}});var d=n(139);Object.defineProperty(t,"List",{enumerable:!0,get:function(){return d.List}});var f=n(144);Object.defineProperty(t,"MultiGrid",{enumerable:!0,get:function(){return f.MultiGrid}});var h=n(146);Object.defineProperty(t,"ScrollSync",{enumerable:!0,get:function(){return h.ScrollSync}});var _=n(148);Object.defineProperty(t,"WindowScroller",{enumerable:!0,get:function(){return _.WindowScroller}})},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.ArrowKeyStepper=t.default=void 0;var i=n(2),r=o(i);t.default=r.default,t.ArrowKeyStepper=r.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(3),r=o(i),l=n(29),a=o(l),s=n(30),u=o(s),c=n(34),d=o(c),f=n(81),h=o(f),_=n(89),p=o(_),v=function(e){function t(e,n){(0,a.default)(this,t);var o=(0,d.default)(this,(t.__proto__||(0,r.default)(t)).call(this,e,n));return o.state={scrollToColumn:e.scrollToColumn,scrollToRow:e.scrollToRow},o._columnStartIndex=0,o._columnStopIndex=0,o._rowStartIndex=0,o._rowStopIndex=0,o._onKeyDown=o._onKeyDown.bind(o),o._onSectionRendered=o._onSectionRendered.bind(o),o}return(0,h.default)(t,e),(0,u.default)(t,[{key:"componentWillUpdate",value:function(e,t){var n=e.scrollToColumn,o=e.scrollToRow;this.props.scrollToColumn!==n&&this.setState({scrollToColumn:n}),this.props.scrollToRow!==o&&this.setState({scrollToRow:o})}},{key:"render",value:function(){var e=this.props,t=e.className,n=e.children,o=this.state,i=o.scrollToColumn,r=o.scrollToRow;return p.default.createElement("div",{className:t,onKeyDown:this._onKeyDown},n({onSectionRendered:this._onSectionRendered,scrollToColumn:i,scrollToRow:r}))}},{key:"_onKeyDown",value:function(e){var t=this.props,n=t.columnCount,o=t.disabled,i=t.mode,r=t.rowCount;if(!o){var l=this.state,a=l.scrollToColumn,s=l.scrollToRow,u=this.state,c=u.scrollToColumn,d=u.scrollToRow;switch(e.key){case"ArrowDown":d="cells"===i?Math.min(d+1,r-1):Math.min(this._rowStopIndex+1,r-1);break;case"ArrowLeft":c="cells"===i?Math.max(c-1,0):Math.max(this._columnStartIndex-1,0);break;case"ArrowRight":c="cells"===i?Math.min(c+1,n-1):Math.min(this._columnStopIndex+1,n-1);break;case"ArrowUp":d="cells"===i?Math.max(d-1,0):Math.max(this._rowStartIndex-1,0)}c===a&&d===s||(e.preventDefault(),this.setState({scrollToColumn:c,scrollToRow:d}))}}},{key:"_onSectionRendered",value:function(e){var t=e.columnStartIndex,n=e.columnStopIndex,o=e.rowStartIndex,i=e.rowStopIndex;this._columnStartIndex=t,this._columnStopIndex=n,this._rowStartIndex=o,this._rowStopIndex=i}}]),t}(_.PureComponent);v.defaultProps={disabled:!1,mode:"edges",scrollToColumn:0,scrollToRow:0},t.default=v},function(e,t,n){e.exports={default:n(4),__esModule:!0}},function(e,t,n){n(5),e.exports=n(16).Object.getPrototypeOf},function(e,t,n){var o=n(6),i=n(8);n(14)("getPrototypeOf",function(){return function(e){return i(o(e))}})},function(e,t,n){var o=n(7);e.exports=function(e){return Object(o(e))}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,n){var o=n(9),i=n(6),r=n(10)("IE_PROTO"),l=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=i(e),o(e,r)?e[r]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?l:null}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var o=n(11)("keys"),i=n(13);e.exports=function(e){return o[e]||(o[e]=i(e))}},function(e,t,n){var o=n(12),i="__core-js_shared__",r=o[i]||(o[i]={});e.exports=function(e){return r[e]||(r[e]={})}},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t){var n=0,o=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+o).toString(36))}},function(e,t,n){var o=n(15),i=n(16),r=n(25);e.exports=function(e,t){var n=(i.Object||{})[e]||Object[e],l={};l[e]=t(n),o(o.S+o.F*r(function(){n(1)}),"Object",l)}},function(e,t,n){var o=n(12),i=n(16),r=n(17),l=n(19),a="prototype",s=function(e,t,n){var u,c,d,f=e&s.F,h=e&s.G,_=e&s.S,p=e&s.P,v=e&s.B,m=e&s.W,g=h?i:i[t]||(i[t]={}),S=g[a],y=h?o:_?o[t]:(o[t]||{})[a];h&&(n=t);for(u in n)c=!f&&y&&void 0!==y[u],c&&u in g||(d=c?y[u]:n[u],g[u]=h&&"function"!=typeof y[u]?n[u]:v&&c?r(d,o):m&&y[u]==d?function(e){var t=function(t,n,o){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,o)}return e.apply(this,arguments)};return t[a]=e[a],t}(d):p&&"function"==typeof d?r(Function.call,d):d,p&&((g.virtual||(g.virtual={}))[u]=d,e&s.R&&S&&!S[u]&&l(S,u,d)))};s.F=1,s.G=2,s.S=4,s.P=8,s.B=16,s.W=32,s.U=64,s.R=128,e.exports=s},function(e,t){var n=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(e,t,n){var o=n(18);e.exports=function(e,t,n){if(o(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,o){return e.call(t,n,o)};case 3:return function(n,o,i){return e.call(t,n,o,i)}}return function(){return e.apply(t,arguments)}}},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,n){var o=n(20),i=n(28);e.exports=n(24)?function(e,t,n){return o.f(e,t,i(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var o=n(21),i=n(23),r=n(27),l=Object.defineProperty;t.f=n(24)?Object.defineProperty:function(e,t,n){if(o(e),t=r(t,!0),o(n),i)try{return l(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){var o=n(22);e.exports=function(e){if(!o(e))throw TypeError(e+" is not an object!");return e}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,n){e.exports=!n(24)&&!n(25)(function(){return 7!=Object.defineProperty(n(26)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){e.exports=!n(25)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,n){var o=n(22),i=n(12).document,r=o(i)&&o(i.createElement);e.exports=function(e){return r?i.createElement(e):{}}},function(e,t,n){var o=n(22);e.exports=function(e,t){if(!o(e))return e;var n,i;if(t&&"function"==typeof(n=e.toString)&&!o(i=n.call(e)))return i;if("function"==typeof(n=e.valueOf)&&!o(i=n.call(e)))return i;if(!t&&"function"==typeof(n=e.toString)&&!o(i=n.call(e)))return i;throw TypeError("Can't convert object to primitive value")}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(31),r=o(i);t.default=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),(0,r.default)(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}()},function(e,t,n){e.exports={default:n(32),__esModule:!0}},function(e,t,n){n(33);var o=n(16).Object;e.exports=function(e,t,n){return o.defineProperty(e,t,n)}},function(e,t,n){var o=n(15);o(o.S+o.F*!n(24),"Object",{defineProperty:n(20).f})},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(35),r=o(i);t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==("undefined"==typeof t?"undefined":(0,r.default)(t))&&"function"!=typeof t?e:t}},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(36),r=o(i),l=n(65),a=o(l),s="function"==typeof a.default&&"symbol"==typeof r.default?function(e){return typeof e}:function(e){return e&&"function"==typeof a.default&&e.constructor===a.default&&e!==a.default.prototype?"symbol":typeof e};t.default="function"==typeof a.default&&"symbol"===s(r.default)?function(e){return"undefined"==typeof e?"undefined":s(e)}:function(e){return e&&"function"==typeof a.default&&e.constructor===a.default&&e!==a.default.prototype?"symbol":"undefined"==typeof e?"undefined":s(e)}},function(e,t,n){e.exports={default:n(37),__esModule:!0}},function(e,t,n){n(38),n(60),e.exports=n(64).f("iterator")},function(e,t,n){"use strict";var o=n(39)(!0);n(41)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=o(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){var o=n(40),i=n(7);e.exports=function(e){return function(t,n){var r,l,a=String(i(t)),s=o(n),u=a.length;return s<0||s>=u?e?"":void 0:(r=a.charCodeAt(s),r<55296||r>56319||s+1===u||(l=a.charCodeAt(s+1))<56320||l>57343?e?a.charAt(s):r:e?a.slice(s,s+2):(r-55296<<10)+(l-56320)+65536)}}},function(e,t){var n=Math.ceil,o=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?o:n)(e)}},function(e,t,n){"use strict";var o=n(42),i=n(15),r=n(43),l=n(19),a=n(9),s=n(44),u=n(45),c=n(58),d=n(8),f=n(59)("iterator"),h=!([].keys&&"next"in[].keys()),_="@@iterator",p="keys",v="values",m=function(){return this};e.exports=function(e,t,n,g,S,y,C){u(n,t,g);var w,x,R,b=function(e){if(!h&&e in I)return I[e];switch(e){case p:return function(){return new n(this,e)};case v:return function(){return new n(this,e)}}return function(){return new n(this,e)}},T=t+" Iterator",z=S==v,M=!1,I=e.prototype,O=I[f]||I[_]||S&&I[S],k=O||b(S),P=S?z?b("entries"):k:void 0,L="Array"==t?I.entries||O:O;if(L&&(R=d(L.call(new e)),R!==Object.prototype&&(c(R,T,!0),o||a(R,f)||l(R,f,m))),z&&O&&O.name!==v&&(M=!0,k=function(){return O.call(this)}),o&&!C||!h&&!M&&I[f]||l(I,f,k),s[t]=k,s[T]=m,S)if(w={values:z?k:b(v),keys:y?k:b(p),entries:P},C)for(x in w)x in I||r(I,x,w[x]);else i(i.P+i.F*(h||M),t,w);return w}},function(e,t){e.exports=!0},function(e,t,n){e.exports=n(19)},function(e,t){e.exports={}},function(e,t,n){"use strict";var o=n(46),i=n(28),r=n(58),l={};n(19)(l,n(59)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=o(l,{next:i(1,n)}),r(e,t+" Iterator")}},function(e,t,n){var o=n(21),i=n(47),r=n(56),l=n(10)("IE_PROTO"),a=function(){},s="prototype",u=function(){var e,t=n(26)("iframe"),o=r.length,i="<",l=">";for(t.style.display="none",n(57).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(i+"script"+l+"document.F=Object"+i+"/script"+l),e.close(),u=e.F;o--;)delete u[s][r[o]];return u()};e.exports=Object.create||function(e,t){var n;return null!==e?(a[s]=o(e),n=new a,a[s]=null,n[l]=e):n=u(),void 0===t?n:i(n,t)}},function(e,t,n){var o=n(20),i=n(21),r=n(48);e.exports=n(24)?Object.defineProperties:function(e,t){i(e);for(var n,l=r(t),a=l.length,s=0;a>s;)o.f(e,n=l[s++],t[n]);return e}},function(e,t,n){var o=n(49),i=n(56);e.exports=Object.keys||function(e){return o(e,i)}},function(e,t,n){var o=n(9),i=n(50),r=n(53)(!1),l=n(10)("IE_PROTO");e.exports=function(e,t){var n,a=i(e),s=0,u=[];for(n in a)n!=l&&o(a,n)&&u.push(n);for(;t.length>s;)o(a,n=t[s++])&&(~r(u,n)||u.push(n));return u}},function(e,t,n){var o=n(51),i=n(7);e.exports=function(e){return o(i(e))}},function(e,t,n){var o=n(52);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==o(e)?e.split(""):Object(e)}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var o=n(50),i=n(54),r=n(55);e.exports=function(e){return function(t,n,l){var a,s=o(t),u=i(s.length),c=r(l,u);if(e&&n!=n){for(;u>c;)if(a=s[c++],a!=a)return!0}else for(;u>c;c++)if((e||c in s)&&s[c]===n)return e||c||0;return!e&&-1}}},function(e,t,n){var o=n(40),i=Math.min;e.exports=function(e){return e>0?i(o(e),9007199254740991):0}},function(e,t,n){var o=n(40),i=Math.max,r=Math.min;e.exports=function(e,t){return e=o(e),e<0?i(e+t,0):r(e,t)}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){e.exports=n(12).document&&document.documentElement},function(e,t,n){var o=n(20).f,i=n(9),r=n(59)("toStringTag");e.exports=function(e,t,n){e&&!i(e=n?e:e.prototype,r)&&o(e,r,{configurable:!0,value:t})}},function(e,t,n){var o=n(11)("wks"),i=n(13),r=n(12).Symbol,l="function"==typeof r,a=e.exports=function(e){return o[e]||(o[e]=l&&r[e]||(l?r:i)("Symbol."+e))};a.store=o},function(e,t,n){n(61);for(var o=n(12),i=n(19),r=n(44),l=n(59)("toStringTag"),a=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],s=0;s<5;s++){var u=a[s],c=o[u],d=c&&c.prototype;d&&!d[l]&&i(d,l,u),r[u]=r.Array}},function(e,t,n){"use strict";var o=n(62),i=n(63),r=n(44),l=n(50);e.exports=n(41)(Array,"Array",function(e,t){this._t=l(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,i(1)):"keys"==t?i(0,n):"values"==t?i(0,e[n]):i(0,[n,e[n]])},"values"),r.Arguments=r.Array,o("keys"),o("values"),o("entries")},function(e,t){e.exports=function(){}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){t.f=n(59)},function(e,t,n){e.exports={default:n(66),__esModule:!0}},function(e,t,n){n(67),n(78),n(79),n(80),e.exports=n(16).Symbol},function(e,t,n){"use strict";var o=n(12),i=n(9),r=n(24),l=n(15),a=n(43),s=n(68).KEY,u=n(25),c=n(11),d=n(58),f=n(13),h=n(59),_=n(64),p=n(69),v=n(70),m=n(71),g=n(74),S=n(21),y=n(50),C=n(27),w=n(28),x=n(46),R=n(75),b=n(77),T=n(20),z=n(48),M=b.f,I=T.f,O=R.f,k=o.Symbol,P=o.JSON,L=P&&P.stringify,E="prototype",A=h("_hidden"),G=h("toPrimitive"),W={}.propertyIsEnumerable,D=c("symbol-registry"),H=c("symbols"),j=c("op-symbols"),N=Object[E],F="function"==typeof k,U=o.QObject,B=!U||!U[E]||!U[E].findChild,V=r&&u(function(){return 7!=x(I({},"a",{get:function(){return I(this,"a",{value:7}).a}})).a})?function(e,t,n){var o=M(N,t);o&&delete N[t],I(e,t,n),o&&e!==N&&I(N,t,o)}:I,K=function(e){var t=H[e]=x(k[E]);return t._k=e,t},q=F&&"symbol"==typeof k.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof k},Y=function(e,t,n){return e===N&&Y(j,t,n),S(e),t=C(t,!0),S(n),i(H,t)?(n.enumerable?(i(e,A)&&e[A][t]&&(e[A][t]=!1),n=x(n,{enumerable:w(0,!1)})):(i(e,A)||I(e,A,w(1,{})),e[A][t]=!0),V(e,t,n)):I(e,t,n)},Q=function(e,t){S(e);for(var n,o=m(t=y(t)),i=0,r=o.length;r>i;)Y(e,n=o[i++],t[n]);return e},X=function(e,t){return void 0===t?x(e):Q(x(e),t)},J=function(e){var t=W.call(this,e=C(e,!0));return!(this===N&&i(H,e)&&!i(j,e))&&(!(t||!i(this,e)||!i(H,e)||i(this,A)&&this[A][e])||t)},Z=function(e,t){if(e=y(e),t=C(t,!0),e!==N||!i(H,t)||i(j,t)){var n=M(e,t);return!n||!i(H,t)||i(e,A)&&e[A][t]||(n.enumerable=!0),n}},$=function(e){for(var t,n=O(y(e)),o=[],r=0;n.length>r;)i(H,t=n[r++])||t==A||t==s||o.push(t);return o},ee=function(e){for(var t,n=e===N,o=O(n?j:y(e)),r=[],l=0;o.length>l;)!i(H,t=o[l++])||n&&!i(N,t)||r.push(H[t]);return r};F||(k=function(){if(this instanceof k)throw TypeError("Symbol is not a constructor!");var e=f(arguments.length>0?arguments[0]:void 0),t=function(n){this===N&&t.call(j,n),i(this,A)&&i(this[A],e)&&(this[A][e]=!1),V(this,e,w(1,n))};return r&&B&&V(N,e,{configurable:!0,set:t}),K(e)},a(k[E],"toString",function(){return this._k}),b.f=Z,T.f=Y,n(76).f=R.f=$,n(73).f=J,n(72).f=ee,r&&!n(42)&&a(N,"propertyIsEnumerable",J,!0),_.f=function(e){return K(h(e))}),l(l.G+l.W+l.F*!F,{Symbol:k});for(var te="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ne=0;te.length>ne;)h(te[ne++]);for(var te=z(h.store),ne=0;te.length>ne;)p(te[ne++]);l(l.S+l.F*!F,"Symbol",{for:function(e){return i(D,e+="")?D[e]:D[e]=k(e)},keyFor:function(e){if(q(e))return v(D,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){B=!0},useSimple:function(){B=!1}}),l(l.S+l.F*!F,"Object",{create:X,defineProperty:Y,defineProperties:Q,getOwnPropertyDescriptor:Z,getOwnPropertyNames:$,getOwnPropertySymbols:ee}),P&&l(l.S+l.F*(!F||u(function(){var e=k();return"[null]"!=L([e])||"{}"!=L({a:e})||"{}"!=L(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!q(e)){for(var t,n,o=[e],i=1;arguments.length>i;)o.push(arguments[i++]);return t=o[1],"function"==typeof t&&(n=t),!n&&g(t)||(t=function(e,t){if(n&&(t=n.call(this,e,t)),!q(t))return t}),o[1]=t,L.apply(P,o)}}}),k[E][G]||n(19)(k[E],G,k[E].valueOf),d(k,"Symbol"),d(Math,"Math",!0),d(o.JSON,"JSON",!0)},function(e,t,n){var o=n(13)("meta"),i=n(22),r=n(9),l=n(20).f,a=0,s=Object.isExtensible||function(){return!0},u=!n(25)(function(){return s(Object.preventExtensions({}))}),c=function(e){l(e,o,{value:{i:"O"+ ++a,w:{}}})},d=function(e,t){if(!i(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!r(e,o)){if(!s(e))return"F";if(!t)return"E";c(e)}return e[o].i},f=function(e,t){if(!r(e,o)){if(!s(e))return!0;if(!t)return!1;c(e)}return e[o].w},h=function(e){return u&&_.NEED&&s(e)&&!r(e,o)&&c(e),e},_=e.exports={KEY:o,NEED:!1,fastKey:d,getWeak:f,onFreeze:h}},function(e,t,n){var o=n(12),i=n(16),r=n(42),l=n(64),a=n(20).f;e.exports=function(e){var t=i.Symbol||(i.Symbol=r?{}:o.Symbol||{});"_"==e.charAt(0)||e in t||a(t,e,{value:l.f(e)})}},function(e,t,n){var o=n(48),i=n(50);e.exports=function(e,t){for(var n,r=i(e),l=o(r),a=l.length,s=0;a>s;)if(r[n=l[s++]]===t)return n}},function(e,t,n){var o=n(48),i=n(72),r=n(73);e.exports=function(e){var t=o(e),n=i.f;if(n)for(var l,a=n(e),s=r.f,u=0;a.length>u;)s.call(e,l=a[u++])&&t.push(l);return t}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var o=n(52);e.exports=Array.isArray||function(e){return"Array"==o(e)}},function(e,t,n){var o=n(50),i=n(76).f,r={}.toString,l="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],a=function(e){try{return i(e)}catch(e){return l.slice()}};e.exports.f=function(e){return l&&"[object Window]"==r.call(e)?a(e):i(o(e))}},function(e,t,n){var o=n(49),i=n(56).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return o(e,i)}},function(e,t,n){var o=n(73),i=n(28),r=n(50),l=n(27),a=n(9),s=n(23),u=Object.getOwnPropertyDescriptor;t.f=n(24)?u:function(e,t){if(e=r(e),t=l(t,!0),s)try{return u(e,t)}catch(e){}if(a(e,t))return i(!o.f.call(e,t),e[t])}},function(e,t){},function(e,t,n){n(69)("asyncIterator")},function(e,t,n){n(69)("observable")},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(82),r=o(i),l=n(86),a=o(l),s=n(35),u=o(s);t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+("undefined"==typeof t?"undefined":(0,u.default)(t)));e.prototype=(0,a.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(r.default?(0,r.default)(e,t):e.__proto__=t)}},function(e,t,n){e.exports={default:n(83),__esModule:!0}},function(e,t,n){n(84),e.exports=n(16).Object.setPrototypeOf},function(e,t,n){var o=n(15);o(o.S,"Object",{setPrototypeOf:n(85).set})},function(e,t,n){var o=n(22),i=n(21),r=function(e,t){if(i(e),!o(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,o){try{o=n(17)(Function.call,n(77).f(Object.prototype,"__proto__").set,2),o(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,n){return r(e,n),t?e.__proto__=n:o(e,n),e}}({},!1):void 0),check:r}},function(e,t,n){e.exports={default:n(87),__esModule:!0}},function(e,t,n){n(88);var o=n(16).Object;e.exports=function(e,t){return o.create(e,t)}},function(e,t,n){var o=n(15);o(o.S,"Object",{create:n(46)})},function(t,n){t.exports=e},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.AutoSizer=t.default=void 0;var i=n(91),r=o(i);t.default=r.default,t.AutoSizer=r.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(3),r=o(i),l=n(29),a=o(l),s=n(30),u=o(s),c=n(34),d=o(c),f=n(81),h=o(f),_=n(89),p=o(_),v=n(92),m=o(v),g=function(e){function t(e){(0,a.default)(this,t);var n=(0,d.default)(this,(t.__proto__||(0,r.default)(t)).call(this,e));return n.state={height:0,width:0},n._onResize=n._onResize.bind(n),n._setRef=n._setRef.bind(n),n}return(0,h.default)(t,e),(0,u.default)(t,[{key:"componentDidMount",value:function(){this._parentNode=this._autoSizer.parentNode,this._detectElementResize=(0,m.default)(),this._detectElementResize.addResizeListener(this._parentNode,this._onResize),this._onResize()}},{key:"componentWillUnmount",value:function(){this._detectElementResize&&this._detectElementResize.removeResizeListener(this._parentNode,this._onResize)}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.disableHeight,o=e.disableWidth,i=this.state,r=i.height,l=i.width,a={overflow:"visible"};return n||(a.height=0),o||(a.width=0),p.default.createElement("div",{ref:this._setRef,style:a},t({height:r,width:l}))}},{key:"_onResize",value:function(){var e=this.props.onResize,t=this._parentNode.getBoundingClientRect(),n=t.height||0,o=t.width||0,i=window.getComputedStyle(this._parentNode)||{},r=parseInt(i.paddingLeft,10)||0,l=parseInt(i.paddingRight,10)||0,a=parseInt(i.paddingTop,10)||0,s=parseInt(i.paddingBottom,10)||0;this.setState({height:n-a-s,width:o-r-l}),e({height:n,width:o})}},{key:"_setRef",value:function(e){this._autoSizer=e}}]),t}(_.PureComponent);g.defaultProps={onResize:function(){}},t.default=g},function(e,t){"use strict";function n(){var e;e="undefined"!=typeof window?window:"undefined"!=typeof self?self:this;var t="undefined"!=typeof document&&document.attachEvent;if(!t){var n=function(){var t=e.requestAnimationFrame||e.mozRequestAnimationFrame||e.webkitRequestAnimationFrame||function(t){return e.setTimeout(t,20)};return function(e){return t(e)}}(),o=function(){var t=e.cancelAnimationFrame||e.mozCancelAnimationFrame||e.webkitCancelAnimationFrame||e.clearTimeout;return function(e){return t(e)}}(),i=function(e){var t=e.__resizeTriggers__,n=t.firstElementChild,o=t.lastElementChild,i=n.firstElementChild;o.scrollLeft=o.scrollWidth,o.scrollTop=o.scrollHeight,i.style.width=n.offsetWidth+1+"px",i.style.height=n.offsetHeight+1+"px",n.scrollLeft=n.scrollWidth,n.scrollTop=n.scrollHeight},r=function(e){return e.offsetWidth!=e.__resizeLast__.width||e.offsetHeight!=e.__resizeLast__.height},l=function(e){if(!(e.target.className.indexOf("contract-trigger")<0&&e.target.className.indexOf("expand-trigger")<0)){var t=this;i(this),this.__resizeRAF__&&o(this.__resizeRAF__),this.__resizeRAF__=n(function(){r(t)&&(t.__resizeLast__.width=t.offsetWidth,t.__resizeLast__.height=t.offsetHeight,t.__resizeListeners__.forEach(function(n){n.call(t,e)}))})}},a=!1,s="animation",u="",c="animationstart",d="Webkit Moz O ms".split(" "),f="webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "),h="",_=document.createElement("fakeelement");if(void 0!==_.style.animationName&&(a=!0),a===!1)for(var p=0;p<d.length;p++)if(void 0!==_.style[d[p]+"AnimationName"]){h=d[p],s=h+"Animation",u="-"+h.toLowerCase()+"-",c=f[p],a=!0;break}var v="resizeanim",m="@"+u+"keyframes "+v+" { from { opacity: 0; } to { opacity: 0; } } ",g=u+"animation: 1ms "+v+"; "}var S=function(){if(!document.getElementById("detectElementResize")){var e=(m?m:"")+".resize-triggers { "+(g?g:"")+'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%; }',t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.id="detectElementResize",n.type="text/css",n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e)),t.appendChild(n)}},y=function(n,o){if(t)n.attachEvent("onresize",o);else{if(!n.__resizeTriggers__){var r=e.getComputedStyle(n);r&&"static"==r.position&&(n.style.position="relative"),S(),n.__resizeLast__={},n.__resizeListeners__=[],(n.__resizeTriggers__=document.createElement("div")).className="resize-triggers",n.__resizeTriggers__.innerHTML='<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>',n.appendChild(n.__resizeTriggers__),i(n),n.addEventListener("scroll",l,!0),c&&(n.__resizeTriggers__.__animationListener__=function(e){e.animationName==v&&i(n)},n.__resizeTriggers__.addEventListener(c,n.__resizeTriggers__.__animationListener__))}n.__resizeListeners__.push(o)}},C=function(e,n){if(t)e.detachEvent("onresize",n);else if(e.__resizeListeners__.splice(e.__resizeListeners__.indexOf(n),1),!e.__resizeListeners__.length){e.removeEventListener("scroll",l,!0),e.__resizeTriggers__.__animationListener__&&(e.__resizeTriggers__.removeEventListener(c,e.__resizeTriggers__.__animationListener__),e.__resizeTriggers__.__animationListener__=null);try{e.__resizeTriggers__=!e.removeChild(e.__resizeTriggers__)}catch(e){}}};return{addResizeListener:y,removeResizeListener:C}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.CellMeasurerCache=t.CellMeasurer=t.default=void 0;var i=n(94),r=o(i),l=n(97),a=o(l);t.default=r.default,t.CellMeasurer=r.default,t.CellMeasurerCache=a.default},function(e,t,n){(function(e){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function i(t){"production"!==e.env.NODE_ENV&&t&&void 0===t.props.deferredMeasurementCache&&console.warn("CellMeasurer should be rendered within a Grid that has a deferredMeasurementCache prop.")}Object.defineProperty(t,"__esModule",{value:!0});var r=n(3),l=o(r),a=n(29),s=o(a),u=n(30),c=o(u),d=n(34),f=o(d),h=n(81),_=o(h),p=n(89),v=n(96),m={},g=function(t){function n(e,t){(0,s.default)(this,n);var o=(0,f.default)(this,(n.__proto__||(0,l.default)(n)).call(this,e,t));return o._measure=o._measure.bind(o),o}return(0,_.default)(n,t),(0,c.default)(n,[{key:"componentDidMount",value:function(){this._maybeMeasureCell()}},{key:"componentDidUpdate",value:function(e,t){this._maybeMeasureCell()}},{key:"render",value:function(){var t=this.props.children;if("production"!==e.env.NODE_ENV){var n=this.props.parent;i(n)}return"function"==typeof t?t({measure:this._measure}):t}},{key:"_maybeMeasureCell",value:function(){var e=this.props,t=e.cache,n=e.columnIndex,o=e.parent,i=e.rowIndex;if(!t.has(i,n)){var r=(0,v.findDOMNode)(this),l=r.offsetHeight,a=r.offsetWidth;t.set(i,n,a,l),void 0!==o&&o.invalidateCellSizeAfterRender({columnIndex:n,rowIndex:i})}}},{key:"_measure",value:function(){var e=(arguments.length>0&&void 0!==arguments[0]&&arguments[0],this.props),t=e.cache,n=e.columnIndex,o=e.parent,i=e.rowIndex,r=(0,v.findDOMNode)(this),l=r.offsetHeight,a=r.offsetWidth;l===t.getHeight(i,n)&&a===t.getWidth(i,n)||(t.set(i,n,a,l),o.recomputeGridSize({columnIndex:n,rowIndex:i}))}}]),n}(p.PureComponent);g.defaultProps={style:m},t.default=g}).call(t,n(95))},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function i(e){if(c===setTimeout)return setTimeout(e,0);if((c===n||!c)&&setTimeout)return c=setTimeout,setTimeout(e,0);try{return c(e,0)}catch(t){try{return c.call(null,e,0)}catch(t){return c.call(this,e,0)}}}function r(e){if(d===clearTimeout)return clearTimeout(e);if((d===o||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(t){try{return d.call(null,e)}catch(t){return d.call(this,e)}}}function l(){p&&h&&(p=!1,h.length?_=h.concat(_):v=-1,_.length&&a())}function a(){if(!p){var e=i(l);p=!0;for(var t=_.length;t;){for(h=_,_=[];++v<t;)h&&h[v].run();v=-1,t=_.length}h=null,p=!1,r(e)}}function s(e,t){this.fun=e,this.array=t}function u(){}var c,d,f=e.exports={};!function(){try{c="function"==typeof setTimeout?setTimeout:n}catch(e){c=n}try{d="function"==typeof clearTimeout?clearTimeout:o}catch(e){d=o}}();var h,_=[],p=!1,v=-1;f.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];_.push(new s(e,t)),1!==_.length||p||i(a)},s.prototype.run=function(){this.fun.apply(null,this.array)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=u,f.addListener=u,f.once=u,f.off=u,f.removeListener=u,f.removeAllListeners=u,f.emit=u,f.binding=function(e){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(e){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},function(e,n){e.exports=t},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function i(e,t){return e+"-"+t}Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_WIDTH=t.DEFAULT_HEIGHT=void 0;var r=n(29),l=o(r),a=n(30),s=o(a),u=t.DEFAULT_HEIGHT=30,c=t.DEFAULT_WIDTH=100,d=function(){function e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,l.default)(this,e),this.columnWidth=function(e){var n=e.index;return t._columnWidthCache.hasOwnProperty(n)?t._columnWidthCache[n]:t._defaultWidth;
},this.rowHeight=function(e){var n=e.index;return t._rowHeightCache.hasOwnProperty(n)?t._rowHeightCache[n]:t._defaultHeight};var o=n.defaultHeight,r=n.defaultWidth,a=n.fixedHeight,s=n.fixedWidth,d=n.keyMapper,f=n.minHeight,h=n.minWidth;this._hasFixedHeight=a===!0,this._hasFixedWidth=s===!0,this._minHeight=f||0,this._minWidth=h||0,this._keyMapper=d||i,this._defaultHeight=Math.max(this._minHeight,o||u),this._defaultWidth=Math.max(this._minWidth,r||c),this._columnCount=0,this._rowCount=0,this._cellHeightCache={},this._cellWidthCache={},this._columnWidthCache={},this._rowHeightCache={}}return(0,s.default)(e,[{key:"clear",value:function(e,t){var n=this._keyMapper(e,t);delete this._cellHeightCache[n],delete this._cellWidthCache[n]}},{key:"clearAll",value:function(){this._cellHeightCache={},this._cellWidthCache={}}},{key:"hasFixedHeight",value:function(){return this._hasFixedHeight}},{key:"hasFixedWidth",value:function(){return this._hasFixedWidth}},{key:"getHeight",value:function(e,t){var n=this._keyMapper(e,t);return this._cellHeightCache.hasOwnProperty(n)?Math.max(this._minHeight,this._cellHeightCache[n]):this._defaultHeight}},{key:"getWidth",value:function(e,t){var n=this._keyMapper(e,t);return this._cellWidthCache.hasOwnProperty(n)?Math.max(this._minWidth,this._cellWidthCache[n]):this._defaultWidth}},{key:"has",value:function(e,t){var n=this._keyMapper(e,t);return this._cellHeightCache.hasOwnProperty(n)}},{key:"set",value:function(e,t,n,o){var i=this._keyMapper(e,t);t>=this._columnCount&&(this._columnCount=t+1),e>=this._rowCount&&(this._rowCount=e+1),this._cellHeightCache[i]=o,this._cellWidthCache[i]=n;for(var r=0,l=0;l<this._rowCount;l++)r=Math.max(r,this.getWidth(l,t));for(var a=0,s=0;s<this._columnCount;s++)a=Math.max(a,this.getHeight(e,s));this._columnWidthCache[t]=r,this._rowHeightCache[e]=a}}]),e}();t.default=d},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Collection=t.default=void 0;var i=n(99),r=o(i);t.default=r.default,t.Collection=r.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=e.cellCache,n=e.cellRenderer,o=e.cellSizeAndPositionGetter,i=e.indices,r=e.isScrolling;return i.map(function(e){var i=o({index:e}),l={index:e,isScrolling:r,key:e,style:{height:i.height,left:i.x,position:"absolute",top:i.y,width:i.width}};return r?(e in t||(t[e]=n(l)),t[e]):n(l)}).filter(function(e){return!!e})}Object.defineProperty(t,"__esModule",{value:!0});var r=n(100),l=o(r),a=n(105),s=o(a),u=n(3),c=o(u),d=n(29),f=o(d),h=n(30),_=o(h),p=n(34),v=o(p),m=n(81),g=o(m),S=n(89),y=o(S),C=n(106),w=o(C),x=n(114),R=o(x),b=n(117),T=o(b),z=function(e){function t(e,n){(0,f.default)(this,t);var o=(0,v.default)(this,(t.__proto__||(0,c.default)(t)).call(this,e,n));return o._cellMetadata=[],o._lastRenderedCellIndices=[],o._cellCache=[],o._isScrollingChange=o._isScrollingChange.bind(o),o._setCollectionViewRef=o._setCollectionViewRef.bind(o),o}return(0,g.default)(t,e),(0,_.default)(t,[{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 e=(0,s.default)(this.props,[]);return y.default.createElement(w.default,(0,l.default)({cellLayoutManager:this,isScrollingChange:this._isScrollingChange,ref:this._setCollectionViewRef},e))}},{key:"calculateSizeAndPositionData",value:function(){var e=this.props,t=e.cellCount,n=e.cellSizeAndPositionGetter,o=e.sectionSize,i=(0,R.default)({cellCount:t,cellSizeAndPositionGetter:n,sectionSize:o});this._cellMetadata=i.cellMetadata,this._sectionManager=i.sectionManager,this._height=i.height,this._width=i.width}},{key:"getLastRenderedIndices",value:function(){return this._lastRenderedCellIndices}},{key:"getScrollPositionForCell",value:function(e){var t=e.align,n=e.cellIndex,o=e.height,i=e.scrollLeft,r=e.scrollTop,l=e.width,a=this.props.cellCount;if(n>=0&&n<a){var s=this._cellMetadata[n];i=(0,T.default)({align:t,cellOffset:s.x,cellSize:s.width,containerSize:l,currentOffset:i,targetIndex:n}),r=(0,T.default)({align:t,cellOffset:s.y,cellSize:s.height,containerSize:o,currentOffset:r,targetIndex:n})}return{scrollLeft:i,scrollTop:r}}},{key:"getTotalSize",value:function(){return{height:this._height,width:this._width}}},{key:"cellRenderers",value:function(e){var t=this,n=e.height,o=e.isScrolling,i=e.width,r=e.x,l=e.y,a=this.props,s=a.cellGroupRenderer,u=a.cellRenderer;return this._lastRenderedCellIndices=this._sectionManager.getCellIndices({height:n,width:i,x:r,y:l}),s({cellCache:this._cellCache,cellRenderer:u,cellSizeAndPositionGetter:function(e){var n=e.index;return t._sectionManager.getCellMetadata({index:n})},indices:this._lastRenderedCellIndices,isScrolling:o})}},{key:"_isScrollingChange",value:function(e){e||(this._cellCache=[])}},{key:"_setCollectionViewRef",value:function(e){this._collectionView=e}}]),t}(S.PureComponent);z.defaultProps={"aria-label":"grid",cellGroupRenderer:i},t.default=z},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(101),r=o(i);t.default=r.default||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e}},function(e,t,n){e.exports={default:n(102),__esModule:!0}},function(e,t,n){n(103),e.exports=n(16).Object.assign},function(e,t,n){var o=n(15);o(o.S+o.F,"Object",{assign:n(104)})},function(e,t,n){"use strict";var o=n(48),i=n(72),r=n(73),l=n(6),a=n(51),s=Object.assign;e.exports=!s||n(25)(function(){var e={},t={},n=Symbol(),o="abcdefghijklmnopqrst";return e[n]=7,o.split("").forEach(function(e){t[e]=e}),7!=s({},e)[n]||Object.keys(s({},t)).join("")!=o})?function(e,t){for(var n=l(e),s=arguments.length,u=1,c=i.f,d=r.f;s>u;)for(var f,h=a(arguments[u++]),_=c?o(h).concat(c(h)):o(h),p=_.length,v=0;p>v;)d.call(h,f=_[v++])&&(n[f]=h[f]);return n}:s},function(e,t){"use strict";t.__esModule=!0,t.default=function(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n}},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(100),r=o(i),l=n(3),a=o(l),s=n(29),u=o(s),c=n(30),d=o(c),f=n(34),h=o(f),_=n(81),p=o(_),v=n(89),m=o(v),g=n(107),S=o(g),y=n(108),C=o(y),w=n(112),x=o(w),R=150,b={OBSERVED:"observed",REQUESTED:"requested"},T=function(e){function t(e,n){(0,u.default)(this,t);var o=(0,h.default)(this,(t.__proto__||(0,a.default)(t)).call(this,e,n));return o.state={calculateSizeAndPositionDataOnNextUpdate:!1,isScrolling:!1,scrollLeft:0,scrollTop:0},o._onSectionRenderedMemoizer=(0,C.default)(),o._onScrollMemoizer=(0,C.default)(!1),o._invokeOnSectionRenderedHelper=o._invokeOnSectionRenderedHelper.bind(o),o._onScroll=o._onScroll.bind(o),o._setScrollingContainerRef=o._setScrollingContainerRef.bind(o),o._updateScrollPositionForScrollToCell=o._updateScrollPositionForScrollToCell.bind(o),o}return(0,p.default)(t,e),(0,d.default)(t,[{key:"recomputeCellSizesAndPositions",value:function(){this.setState({calculateSizeAndPositionDataOnNextUpdate:!0})}},{key:"componentDidMount",value:function(){var e=this.props,t=e.cellLayoutManager,n=e.scrollLeft,o=e.scrollToCell,i=e.scrollTop;this._scrollbarSizeMeasured||(this._scrollbarSize=(0,x.default)(),this._scrollbarSizeMeasured=!0,this.setState({})),o>=0?this._updateScrollPositionForScrollToCell():(n>=0||i>=0)&&this._setScrollPosition({scrollLeft:n,scrollTop:i}),this._invokeOnSectionRenderedHelper();var r=t.getTotalSize(),l=r.height,a=r.width;this._invokeOnScrollMemoizer({scrollLeft:n||0,scrollTop:i||0,totalHeight:l,totalWidth:a})}},{key:"componentDidUpdate",value:function(e,t){var n=this.props,o=n.height,i=n.scrollToAlignment,r=n.scrollToCell,l=n.width,a=this.state,s=a.scrollLeft,u=a.scrollPositionChangeReason,c=a.scrollTop;u===b.REQUESTED&&(s>=0&&s!==t.scrollLeft&&s!==this._scrollingContainer.scrollLeft&&(this._scrollingContainer.scrollLeft=s),c>=0&&c!==t.scrollTop&&c!==this._scrollingContainer.scrollTop&&(this._scrollingContainer.scrollTop=c)),o===e.height&&i===e.scrollToAlignment&&r===e.scrollToCell&&l===e.width||this._updateScrollPositionForScrollToCell(),this._invokeOnSectionRenderedHelper()}},{key:"componentWillMount",value:function(){var e=this.props.cellLayoutManager;e.calculateSizeAndPositionData(),this._scrollbarSize=(0,x.default)(),void 0===this._scrollbarSize?(this._scrollbarSizeMeasured=!1,this._scrollbarSize=0):this._scrollbarSizeMeasured=!0}},{key:"componentWillUnmount",value:function(){this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId)}},{key:"componentWillUpdate",value:function(e,t){0!==e.cellCount||0===t.scrollLeft&&0===t.scrollTop?e.scrollLeft===this.props.scrollLeft&&e.scrollTop===this.props.scrollTop||this._setScrollPosition({scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}):this._setScrollPosition({scrollLeft:0,scrollTop:0}),(e.cellCount!==this.props.cellCount||e.cellLayoutManager!==this.props.cellLayoutManager||t.calculateSizeAndPositionDataOnNextUpdate)&&e.cellLayoutManager.calculateSizeAndPositionData(),t.calculateSizeAndPositionDataOnNextUpdate&&this.setState({calculateSizeAndPositionDataOnNextUpdate:!1})}},{key:"render",value:function(){var e=this.props,t=e.autoHeight,n=e.cellCount,o=e.cellLayoutManager,i=e.className,l=e.height,a=e.horizontalOverscanSize,s=e.id,u=e.noContentRenderer,c=e.style,d=e.verticalOverscanSize,f=e.width,h=this.state,_=h.isScrolling,p=h.scrollLeft,v=h.scrollTop,g=o.getTotalSize(),y=g.height,C=g.width,w=Math.max(0,p-a),x=Math.max(0,v-d),R=Math.min(C,p+f+a),b=Math.min(y,v+l+d),T=l>0&&f>0?o.cellRenderers({height:b-x,isScrolling:_,width:R-w,x:w,y:x}):[],z={boxSizing:"border-box",direction:"ltr",height:t?"auto":l,position:"relative",WebkitOverflowScrolling:"touch",width:f,willChange:"transform"},M=y>l?this._scrollbarSize:0,I=C>f?this._scrollbarSize:0;return z.overflowX=C+M<=f?"hidden":"auto",z.overflowY=y+I<=l?"hidden":"auto",m.default.createElement("div",{ref:this._setScrollingContainerRef,"aria-label":this.props["aria-label"],className:(0,S.default)("ReactVirtualized__Collection",i),id:s,onScroll:this._onScroll,role:"grid",style:(0,r.default)({},z,c),tabIndex:0},n>0&&m.default.createElement("div",{className:"ReactVirtualized__Collection__innerScrollContainer",style:{height:y,maxHeight:y,maxWidth:C,overflow:"hidden",pointerEvents:_?"none":"",width:C}},T),0===n&&u())}},{key:"_enablePointerEventsAfterDelay",value:function(){var e=this;this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._disablePointerEventsTimeoutId=setTimeout(function(){var t=e.props.isScrollingChange;t(!1),e._disablePointerEventsTimeoutId=null,e.setState({isScrolling:!1})},R)}},{key:"_invokeOnSectionRenderedHelper",value:function(){var e=this.props,t=e.cellLayoutManager,n=e.onSectionRendered;this._onSectionRenderedMemoizer({callback:n,indices:{indices:t.getLastRenderedIndices()}})}},{key:"_invokeOnScrollMemoizer",value:function(e){var t=this,n=e.scrollLeft,o=e.scrollTop,i=e.totalHeight,r=e.totalWidth;this._onScrollMemoizer({callback:function(e){var n=e.scrollLeft,o=e.scrollTop,l=t.props,a=l.height,s=l.onScroll,u=l.width;s({clientHeight:a,clientWidth:u,scrollHeight:i,scrollLeft:n,scrollTop:o,scrollWidth:r})},indices:{scrollLeft:n,scrollTop:o}})}},{key:"_setScrollingContainerRef",value:function(e){this._scrollingContainer=e}},{key:"_setScrollPosition",value:function(e){var t=e.scrollLeft,n=e.scrollTop,o={scrollPositionChangeReason:b.REQUESTED};t>=0&&(o.scrollLeft=t),n>=0&&(o.scrollTop=n),(t>=0&&t!==this.state.scrollLeft||n>=0&&n!==this.state.scrollTop)&&this.setState(o)}},{key:"_updateScrollPositionForScrollToCell",value:function(){var e=this.props,t=e.cellLayoutManager,n=e.height,o=e.scrollToAlignment,i=e.scrollToCell,r=e.width,l=this.state,a=l.scrollLeft,s=l.scrollTop;if(i>=0){var u=t.getScrollPositionForCell({align:o,cellIndex:i,height:n,scrollLeft:a,scrollTop:s,width:r});u.scrollLeft===a&&u.scrollTop===s||this._setScrollPosition(u)}}},{key:"_onScroll",value:function(e){if(e.target===this._scrollingContainer){this._enablePointerEventsAfterDelay();var t=this.props,n=t.cellLayoutManager,o=t.height,i=t.isScrollingChange,r=t.width,l=this._scrollbarSize,a=n.getTotalSize(),s=a.height,u=a.width,c=Math.max(0,Math.min(u-r+l,e.target.scrollLeft)),d=Math.max(0,Math.min(s-o+l,e.target.scrollTop));if(this.state.scrollLeft!==c||this.state.scrollTop!==d){var f=e.cancelable?b.OBSERVED:b.REQUESTED;this.state.isScrolling||i(!0),this.setState({isScrolling:!0,scrollLeft:c,scrollPositionChangeReason:f,scrollTop:d})}this._invokeOnScrollMemoizer({scrollLeft:c,scrollTop:d,totalWidth:u,totalHeight:s})}}}]),t}(v.PureComponent);T.defaultProps={"aria-label":"grid",horizontalOverscanSize:0,noContentRenderer:function(){return null},onScroll:function(){return null},onSectionRendered:function(){return null},scrollToAlignment:"auto",style:{},verticalOverscanSize:0},t.default=T},function(e,t,n){var o,i;!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var o=arguments[t];if(o){var i=typeof o;if("string"===i||"number"===i)e.push(o);else if(Array.isArray(o))e.push(n.apply(null,o));else if("object"===i)for(var l in o)r.call(o,l)&&o[l]&&e.push(l)}}return e.join(" ")}var r={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(o=[],i=function(){return n}.apply(t,o),!(void 0!==i&&(e.exports=i)))}()},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function i(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t={};return function(n){var o=n.callback,i=n.indices,r=(0,l.default)(i),a=!e||r.every(function(e){var t=i[e];return Array.isArray(t)?t.length>0:t>=0}),s=r.length!==(0,l.default)(t).length||r.some(function(e){var n=t[e],o=i[e];return Array.isArray(o)?n.join(",")!==o.join(","):n!==o});t=i,a&&s&&o(i)}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(109),l=o(r);t.default=i},function(e,t,n){e.exports={default:n(110),__esModule:!0}},function(e,t,n){n(111),e.exports=n(16).Object.keys},function(e,t,n){var o=n(6),i=n(48);n(14)("keys",function(){return function(e){return i(o(e))}})},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if((!l||e)&&r.default){var t=document.createElement("div");t.style.position="absolute",t.style.top="-9999px",t.style.width="50px",t.style.height="50px",t.style.overflow="scroll",document.body.appendChild(t),l=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return l};var i=n(113),r=o(i),l=void 0;e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=!("undefined"==typeof window||!window.document||!window.document.createElement),e.exports=t.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function i(e){for(var t=e.cellCount,n=e.cellSizeAndPositionGetter,o=e.sectionSize,i=[],r=new l.default(o),a=0,s=0,u=0;u<t;u++){var c=n({index:u});if(null==c.height||isNaN(c.height)||null==c.width||isNaN(c.width)||null==c.x||isNaN(c.x)||null==c.y||isNaN(c.y))throw Error("Invalid metadata returned for cell "+u+":\n x:"+c.x+", y:"+c.y+", width:"+c.width+", height:"+c.height);a=Math.max(a,c.y+c.height),s=Math.max(s,c.x+c.width),i[u]=c,r.registerCell({cellMetadatum:c,index:u})}return{cellMetadata:i,height:a,sectionManager:r,width:s}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var r=n(115),l=o(r)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(109),r=o(i),l=n(29),a=o(l),s=n(30),u=o(s),c=n(116),d=o(c),f=100,h=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:f;(0,a.default)(this,e),this._sectionSize=t,this._cellMetadata=[],this._sections={}}return(0,u.default)(e,[{key:"getCellIndices",value:function(e){var t=e.height,n=e.width,o=e.x,i=e.y,l={};return this.getSections({height:t,width:n,x:o,y:i}).forEach(function(e){return e.getCellIndices().forEach(function(e){l[e]=e})}),(0,r.default)(l).map(function(e){return l[e]})}},{key:"getCellMetadata",value:function(e){var t=e.index;return this._cellMetadata[t]}},{key:"getSections",value:function(e){for(var t=e.height,n=e.width,o=e.x,i=e.y,r=Math.floor(o/this._sectionSize),l=Math.floor((o+n-1)/this._sectionSize),a=Math.floor(i/this._sectionSize),s=Math.floor((i+t-1)/this._sectionSize),u=[],c=r;c<=l;c++)for(var f=a;f<=s;f++){var h=c+"."+f;this._sections[h]||(this._sections[h]=new d.default({height:this._sectionSize,width:this._sectionSize,x:c*this._sectionSize,y:f*this._sectionSize})),u.push(this._sections[h])}return u}},{key:"getTotalSectionCount",value:function(){return(0,r.default)(this._sections).length}},{key:"toString",value:function(){var e=this;return(0,r.default)(this._sections).map(function(t){return e._sections[t].toString()})}},{key:"registerCell",value:function(e){var t=e.cellMetadatum,n=e.index;this._cellMetadata[n]=t,this.getSections(t).forEach(function(e){return e.addCellIndex({index:n})})}}]),e}();t.default=h},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(29),r=o(i),l=n(30),a=o(l),s=function(){function e(t){var n=t.height,o=t.width,i=t.x,l=t.y;(0,r.default)(this,e),this.height=n,this.width=o,this.x=i,this.y=l,this._indexMap={},this._indices=[]}return(0,a.default)(e,[{key:"addCellIndex",value:function(e){var t=e.index;this._indexMap[t]||(this._indexMap[t]=!0,this._indices.push(t))}},{key:"getCellIndices",value:function(){return this._indices}},{key:"toString",value:function(){return this.x+","+this.y+" "+this.width+"x"+this.height}}]),e}();t.default=s},function(e,t){"use strict";function n(e){var t=e.align,n=void 0===t?"auto":t,o=e.cellOffset,i=e.cellSize,r=e.containerSize,l=e.currentOffset,a=o,s=a-r+i;switch(n){case"start":return a;case"end":return s;case"center":return a-(r-i)/2;default:return Math.max(s,Math.min(a,l))}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.ColumnSizer=t.default=void 0;var i=n(119),r=o(i);t.default=r.default,t.ColumnSizer=r.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(3),r=o(i),l=n(29),a=o(l),s=n(30),u=o(s),c=n(34),d=o(c),f=n(81),h=o(f),_=n(89),p=function(e){function t(e,n){(0,a.default)(this,t);var o=(0,d.default)(this,(t.__proto__||(0,r.default)(t)).call(this,e,n));return o._registerChild=o._registerChild.bind(o),o}return(0,h.default)(t,e),(0,u.default)(t,[{key:"componentDidUpdate",value:function(e,t){var n=this.props,o=n.columnMaxWidth,i=n.columnMinWidth,r=n.columnCount,l=n.width;o===e.columnMaxWidth&&i===e.columnMinWidth&&r===e.columnCount&&l===e.width||this._registeredChild&&this._registeredChild.recomputeGridSize()}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.columnMaxWidth,o=e.columnMinWidth,i=e.columnCount,r=e.width,l=o||1,a=n?Math.min(n,r):r,s=r/i;s=Math.max(l,s),s=Math.min(a,s),s=Math.floor(s);var u=Math.min(r,s*i);return t({adjustedWidth:u,getColumnWidth:function(){return s},registerChild:this._registerChild})}},{key:"_registerChild",value:function(e){if(e&&"function"!=typeof e.recomputeGridSize)throw Error("Unexpected child type registered; only Grid/MultiGrid children are supported.");this._registeredChild=e,this._registeredChild&&this._registeredChild.recomputeGridSize()}}]),t}(_.PureComponent);t.default=p},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.SortIndicator=t.SortDirection=t.Column=t.Table=t.defaultRowRenderer=t.defaultHeaderRenderer=t.defaultCellRenderer=t.defaultCellDataGetter=t.default=void 0;var i=n(121),r=o(i),l=n(127),a=o(l),s=n(126),u=o(s),c=n(123),d=o(c),f=n(136),h=o(f),_=n(122),p=o(_),v=n(125),m=o(v),g=n(124),S=o(g);t.default=r.default,t.defaultCellDataGetter=a.default,t.defaultCellRenderer=u.default,t.defaultHeaderRenderer=d.default,t.defaultRowRenderer=h.default,t.Table=r.default,t.Column=p.default,t.SortDirection=m.default,t.SortIndicator=S.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(100),r=o(i),l=n(3),a=o(l),s=n(29),u=o(s),c=n(30),d=o(c),f=n(34),h=o(f),_=n(81),p=o(_),v=n(107),m=o(v),g=n(122),S=(o(g),n(89)),y=o(S),C=n(96),w=n(128),x=o(w),R=n(136),b=o(R),T=n(125),z=o(T),M=function(e){function t(e){(0,u.default)(this,t);var n=(0,h.default)(this,(t.__proto__||(0,a.default)(t)).call(this,e));return n.state={scrollbarWidth:0},n._createColumn=n._createColumn.bind(n),n._createRow=n._createRow.bind(n),n._onScroll=n._onScroll.bind(n),n._onSectionRendered=n._onSectionRendered.bind(n),n._setRef=n._setRef.bind(n),n}return(0,p.default)(t,e),(0,d.default)(t,[{key:"forceUpdateGrid",value:function(){this.Grid.forceUpdate()}},{key:"measureAllRows",value:function(){this.Grid.measureAllCells()}},{key:"recomputeRowHeights",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.Grid.recomputeGridSize({rowIndex:e})}},{key:"scrollToRow",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.Grid.scrollToCell({columnIndex:0,rowIndex:e})}},{key:"componentDidMount",value:function(){this._setScrollbarWidth()}},{key:"componentDidUpdate",value:function(){this._setScrollbarWidth()}},{key:"render",value:function(){var e=this,t=this.props,n=t.children,o=t.className,i=t.disableHeader,l=t.gridClassName,a=t.gridStyle,s=t.headerHeight,u=t.height,c=t.id,d=t.noRowsRenderer,f=t.rowClassName,h=t.rowStyle,_=t.scrollToIndex,p=t.style,v=t.width,g=this.state.scrollbarWidth,S=i?u:u-s,C=f instanceof Function?f({index:-1}):f,w=h instanceof Function?h({index:-1}):h;return this._cachedColumnStyles=[],y.default.Children.toArray(n).forEach(function(t,n){var o=e._getFlexStyleForColumn(t,t.props.style);e._cachedColumnStyles[n]=(0,r.default)({},o,{overflow:"hidden"})}),y.default.createElement("div",{className:(0,m.default)("ReactVirtualized__Table",o),id:c,style:p},!i&&y.default.createElement("div",{className:(0,m.default)("ReactVirtualized__Table__headerRow",C),style:(0,r.default)({},w,{height:s,overflow:"hidden",paddingRight:g,width:v})},this._getRenderedHeaderRow()),y.default.createElement(x.default,(0,r.default)({},this.props,{autoContainerWidth:!0,className:(0,m.default)("ReactVirtualized__Table__Grid",l),cellRenderer:this._createRow,columnWidth:v,columnCount:1,height:S,id:void 0,noContentRenderer:d,onScroll:this._onScroll,onSectionRendered:this._onSectionRendered,ref:this._setRef,scrollbarWidth:g,scrollToRow:_,style:(0,r.default)({},a,{overflowX:"hidden"})})))}},{key:"_createColumn",value:function(e){var t=e.column,n=e.columnIndex,o=e.isScrolling,i=e.parent,r=e.rowData,l=e.rowIndex,a=t.props,s=a.cellDataGetter,u=a.cellRenderer,c=a.className,d=a.columnData,f=a.dataKey,h=s({columnData:d,dataKey:f,rowData:r}),_=u({cellData:h,columnData:d,dataKey:f,isScrolling:o,parent:i,rowData:r,rowIndex:l}),p=this._cachedColumnStyles[n],v="string"==typeof _?_:null;return y.default.createElement("div",{key:"Row"+l+"-Col"+n,className:(0,m.default)("ReactVirtualized__Table__rowColumn",c),style:p,title:v},_)}},{key:"_createHeader",value:function(e){var t=e.column,n=e.index,o=this.props,i=o.headerClassName,l=o.headerStyle,a=o.onHeaderClick,s=o.sort,u=o.sortBy,c=o.sortDirection,d=t.props,f=d.dataKey,h=d.disableSort,_=d.headerRenderer,p=d.label,v=d.columnData,g=!h&&s,S=(0,m.default)("ReactVirtualized__Table__headerColumn",i,t.props.headerClassName,{ReactVirtualized__Table__sortableHeaderColumn:g}),C=this._getFlexStyleForColumn(t,l),w=_({columnData:v,dataKey:f,disableSort:h,label:p,sortBy:u,sortDirection:c}),x={};return(g||a)&&!function(){var e=u!==f||c===z.default.DESC?z.default.ASC:z.default.DESC,n=function(){g&&s({sortBy:f,sortDirection:e}),a&&a({columnData:v,dataKey:f})},o=function(e){"Enter"!==e.key&&" "!==e.key||n()};x["aria-label"]=t.props["aria-label"]||p||f,x.role="rowheader",x.tabIndex=0,x.onClick=n,x.onKeyDown=o}(),y.default.createElement("div",(0,r.default)({},x,{key:"Header-Col"+n,className:S,style:C}),w)}},{key:"_createRow",value:function(e){var t=this,n=e.rowIndex,o=e.isScrolling,i=e.key,l=e.parent,a=e.style,s=this.props,u=s.children,c=s.onRowClick,d=s.onRowDoubleClick,f=s.onRowMouseOver,h=s.onRowMouseOut,_=s.rowClassName,p=s.rowGetter,v=s.rowRenderer,g=s.rowStyle,S=this.state.scrollbarWidth,C=_ instanceof Function?_({index:n}):_,w=g instanceof Function?g({index:n}):g,x=p({index:n}),R=y.default.Children.toArray(u).map(function(e,i){return t._createColumn({column:e,columnIndex:i,isScrolling:o,parent:l,rowData:x,rowIndex:n,scrollbarWidth:S})}),b=(0,m.default)("ReactVirtualized__Table__row",C),T=(0,r.default)({},a,w,{height:this._getRowHeight(n),overflow:"hidden",paddingRight:S});return v({className:b,columns:R,index:n,isScrolling:o,key:i,onRowClick:c,onRowDoubleClick:d,onRowMouseOver:f,onRowMouseOut:h,rowData:x,style:T})}},{key:"_getFlexStyleForColumn",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.props.flexGrow+" "+e.props.flexShrink+" "+e.props.width+"px",o=(0,r.default)({},t,{flex:n,msFlex:n,WebkitFlex:n});return e.props.maxWidth&&(o.maxWidth=e.props.maxWidth),e.props.minWidth&&(o.minWidth=e.props.minWidth),o}},{key:"_getRenderedHeaderRow",value:function(){var e=this,t=this.props,n=t.children,o=t.disableHeader,i=o?[]:y.default.Children.toArray(n);return i.map(function(t,n){return e._createHeader({column:t,index:n})})}},{key:"_getRowHeight",value:function(e){var t=this.props.rowHeight;return t instanceof Function?t({index:e}):t}},{key:"_onScroll",value:function(e){var t=e.clientHeight,n=e.scrollHeight,o=e.scrollTop,i=this.props.onScroll;i({clientHeight:t,scrollHeight:n,scrollTop:o})}},{key:"_onSectionRendered",value:function(e){var t=e.rowOverscanStartIndex,n=e.rowOverscanStopIndex,o=e.rowStartIndex,i=e.rowStopIndex,r=this.props.onRowsRendered;r({overscanStartIndex:t,overscanStopIndex:n,startIndex:o,stopIndex:i})}},{key:"_setRef",value:function(e){this.Grid=e}},{key:"_setScrollbarWidth",value:function(){var e=(0,C.findDOMNode)(this.Grid),t=e.clientWidth||0,n=e.offsetWidth||0,o=n-t;this.setState({scrollbarWidth:o})}}]),t}(S.PureComponent);M.defaultProps={disableHeader:!1,estimatedRowSize:30,headerHeight:0,headerStyle:{},noRowsRenderer:function(){return null},onRowsRendered:function(){return null},onScroll:function(){return null},overscanRowCount:10,rowRenderer:b.default,rowStyle:{},scrollToAlignment:"auto",style:{}},t.default=M},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(3),r=o(i),l=n(29),a=o(l),s=n(34),u=o(s),c=n(81),d=o(c),f=n(89),h=n(123),_=o(h),p=n(126),v=o(p),m=n(127),g=o(m),S=function(e){function t(){return(0,a.default)(this,t),(0,u.default)(this,(t.__proto__||(0,r.default)(t)).apply(this,arguments))}return(0,d.default)(t,e),t}(f.Component);S.defaultProps={cellDataGetter:g.default,cellRenderer:v.default,flexGrow:0,flexShrink:1,headerRenderer:_.default,style:{}},t.default=S},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=(e.columnData,e.dataKey),n=(e.disableSort,e.label),o=e.sortBy,i=e.sortDirection,r=o===t,a=[l.default.createElement("span",{className:"ReactVirtualized__Table__headerTruncatedText",key:"label",title:n},n)];return r&&a.push(l.default.createElement(s.default,{key:"SortIndicator",sortDirection:i})),a}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var r=n(89),l=o(r),a=n(124),s=o(a)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=e.sortDirection,n=(0,s.default)("ReactVirtualized__Table__sortableHeaderIcon",{"ReactVirtualized__Table__sortableHeaderIcon--ASC":t===c.default.ASC,"ReactVirtualized__Table__sortableHeaderIcon--DESC":t===c.default.DESC});return l.default.createElement("svg",{className:n,width:18,height:18,viewBox:"0 0 24 24"},t===c.default.ASC?l.default.createElement("path",{d:"M7 14l5-5 5 5z"}):l.default.createElement("path",{d:"M7 10l5 5 5-5z"}),l.default.createElement("path",{d:"M0 0h24v24H0z",fill:"none"}))}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var r=n(89),l=o(r),a=n(107),s=o(a),u=n(125),c=o(u)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={ASC:"ASC",DESC:"DESC"};t.default=n},function(e,t){"use strict";function n(e){var t=e.cellData;return e.cellDataKey,e.columnData,e.rowData,e.rowIndex,null==t?"":String(t)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t){"use strict";function n(e){var t=(e.columnData,e.dataKey),n=e.rowData;return n.get instanceof Function?n.get(t):n[t]}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.defaultCellRangeRenderer=t.Grid=t.default=void 0;var i=n(129),r=o(i),l=n(135),a=o(l);t.default=r.default,t.Grid=r.default,t.defaultCellRangeRenderer=a.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_SCROLLING_RESET_TIME_INTERVAL=void 0;var i=n(100),r=o(i),l=n(3),a=o(l),s=n(29),u=o(s),c=n(30),d=o(c),f=n(34),h=o(f),_=n(81),p=o(_),v=n(89),m=o(v),g=n(107),S=o(g),y=n(130),C=o(y),w=n(131),x=o(w),R=n(108),b=o(R),T=n(133),z=o(T),M=n(112),I=o(M),O=n(134),k=o(O),P=n(135),L=o(P),E=t.DEFAULT_SCROLLING_RESET_TIME_INTERVAL=150,A={OBSERVED:"observed",REQUESTED:"requested"},G=function(e){function t(e,n){(0,u.default)(this,t);var o=(0,h.default)(this,(t.__proto__||(0,a.default)(t)).call(this,e,n));o.state={isScrolling:!1,scrollDirectionHorizontal:T.SCROLL_DIRECTION_FORWARD,scrollDirectionVertical:T.SCROLL_DIRECTION_FORWARD,scrollLeft:0,scrollTop:0},o._onGridRenderedMemoizer=(0,b.default)(),o._onScrollMemoizer=(0,b.default)(!1),o._debounceScrollEndedCallback=o._debounceScrollEndedCallback.bind(o),o._invokeOnGridRenderedHelper=o._invokeOnGridRenderedHelper.bind(o),o._onScroll=o._onScroll.bind(o),o._setScrollingContainerRef=o._setScrollingContainerRef.bind(o),o._updateScrollLeftForScrollToColumn=o._updateScrollLeftForScrollToColumn.bind(o),o._updateScrollTopForScrollToRow=o._updateScrollTopForScrollToRow.bind(o),o._columnWidthGetter=o._wrapSizeGetter(e.columnWidth),o._rowHeightGetter=o._wrapSizeGetter(e.rowHeight),o._deferredInvalidateColumnIndex=null,o._deferredInvalidateRowIndex=null;var i=e.deferredMeasurementCache,r="undefined"!=typeof i;return o._columnSizeAndPositionManager=new x.default({batchAllCells:r&&!i.hasFixedHeight(),cellCount:e.columnCount,cellSizeGetter:function(e){return o._columnWidthGetter(e)},estimatedCellSize:o._getEstimatedColumnSize(e)}),o._rowSizeAndPositionManager=new x.default({batchAllCells:r&&!i.hasFixedWidth(),cellCount:e.rowCount,cellSizeGetter:function(e){return o._rowHeightGetter(e)},estimatedCellSize:o._getEstimatedRowSize(e)}),o._cellCache={},o._styleCache={},o}return(0,p.default)(t,e),(0,d.default)(t,[{key:"invalidateCellSizeAfterRender",value:function(e){var t=e.columnIndex,n=e.rowIndex;this._deferredInvalidateColumnIndex="number"==typeof this._deferredInvalidateColumnIndex?Math.min(this._deferredInvalidateColumnIndex,t):t,this._deferredInvalidateRowIndex="number"==typeof this._deferredInvalidateRowIndex?Math.min(this._deferredInvalidateRowIndex,n):n}},{key:"measureAllCells",value:function(){var e=this.props,t=e.columnCount,n=e.rowCount;this._columnSizeAndPositionManager.getSizeAndPositionOfCell(t-1),
this._rowSizeAndPositionManager.getSizeAndPositionOfCell(n-1)}},{key:"recomputeGridSize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.columnIndex,n=void 0===t?0:t,o=e.rowIndex,i=void 0===o?0:o;this._columnSizeAndPositionManager.resetCell(n),this._rowSizeAndPositionManager.resetCell(i),this._cellCache={},this._styleCache={},this.forceUpdate()}},{key:"scrollToCell",value:function(e){var t=e.columnIndex,n=e.rowIndex,o=this.props;this._updateScrollLeftForScrollToColumn((0,r.default)({},o,{scrollToColumn:t})),this._updateScrollTopForScrollToRow((0,r.default)({},o,{scrollToRow:n}))}},{key:"componentDidMount",value:function(){var e=this.props,t=e.scrollLeft,n=e.scrollToColumn,o=e.scrollTop,i=e.scrollToRow;this._handleInvalidatedGridSize(),this._scrollbarSizeMeasured||(this._scrollbarSize=(0,I.default)(),this._scrollbarSizeMeasured=!0,this.setState({})),(t>=0||o>=0)&&this._setScrollPosition({scrollLeft:t,scrollTop:o}),(n>=0||i>=0)&&(this._updateScrollLeftForScrollToColumn(),this._updateScrollTopForScrollToRow()),this._invokeOnGridRenderedHelper(),this._invokeOnScrollMemoizer({scrollLeft:t||0,scrollTop:o||0,totalColumnsWidth:this._columnSizeAndPositionManager.getTotalSize(),totalRowsHeight:this._rowSizeAndPositionManager.getTotalSize()})}},{key:"componentDidUpdate",value:function(e,t){var n=this,o=this.props,i=o.autoHeight,l=o.columnCount,a=o.height,s=o.rowCount,u=o.scrollToAlignment,c=o.scrollToColumn,d=o.scrollToRow,f=o.width,h=this.state,_=h.scrollLeft,p=h.scrollPositionChangeReason,v=h.scrollTop;this._handleInvalidatedGridSize();var m=l>0&&0===e.columnCount||s>0&&0===e.rowCount;if(p===A.REQUESTED&&(_>=0&&(_!==t.scrollLeft&&_!==this._scrollingContainer.scrollLeft||m)&&(this._scrollingContainer.scrollLeft=_),!i&&v>=0&&(v!==t.scrollTop&&v!==this._scrollingContainer.scrollTop||m)&&(this._scrollingContainer.scrollTop=v)),(0,k.default)({cellSizeAndPositionManager:this._columnSizeAndPositionManager,previousCellsCount:e.columnCount,previousCellSize:e.columnWidth,previousScrollToAlignment:e.scrollToAlignment,previousScrollToIndex:e.scrollToColumn,previousSize:e.width,scrollOffset:_,scrollToAlignment:u,scrollToIndex:c,size:f,updateScrollIndexCallback:function(e){return n._updateScrollLeftForScrollToColumn((0,r.default)({},n.props,{scrollToColumn:e}))}}),(0,k.default)({cellSizeAndPositionManager:this._rowSizeAndPositionManager,previousCellsCount:e.rowCount,previousCellSize:e.rowHeight,previousScrollToAlignment:e.scrollToAlignment,previousScrollToIndex:e.scrollToRow,previousSize:e.height,scrollOffset:v,scrollToAlignment:u,scrollToIndex:d,size:a,updateScrollIndexCallback:function(e){return n._updateScrollTopForScrollToRow((0,r.default)({},n.props,{scrollToRow:e}))}}),this._invokeOnGridRenderedHelper(),_!==t.scrollLeft||v!==t.scrollTop){var g=this._rowSizeAndPositionManager.getTotalSize(),S=this._columnSizeAndPositionManager.getTotalSize();this._invokeOnScrollMemoizer({scrollLeft:_,scrollTop:v,totalColumnsWidth:S,totalRowsHeight:g})}}},{key:"componentWillMount",value:function(){this._scrollbarSize=(0,I.default)(),void 0===this._scrollbarSize?(this._scrollbarSizeMeasured=!1,this._scrollbarSize=0):this._scrollbarSizeMeasured=!0,this._calculateChildrenToRender()}},{key:"componentWillUnmount",value:function(){this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId)}},{key:"componentWillUpdate",value:function(e,t){var n=this;if(0===e.columnCount&&0!==t.scrollLeft||0===e.rowCount&&0!==t.scrollTop)this._setScrollPosition({scrollLeft:0,scrollTop:0});else if(e.scrollLeft!==this.props.scrollLeft||e.scrollTop!==this.props.scrollTop){var o={};null!=e.scrollLeft&&(o.scrollLeft=e.scrollLeft),null!=e.scrollTop&&(o.scrollTop=e.scrollTop),this._setScrollPosition(o)}e.columnWidth===this.props.columnWidth&&e.rowHeight===this.props.rowHeight||(this._styleCache={}),this._columnWidthGetter=this._wrapSizeGetter(e.columnWidth),this._rowHeightGetter=this._wrapSizeGetter(e.rowHeight),this._columnSizeAndPositionManager.configure({cellCount:e.columnCount,estimatedCellSize:this._getEstimatedColumnSize(e)}),this._rowSizeAndPositionManager.configure({cellCount:e.rowCount,estimatedCellSize:this._getEstimatedRowSize(e)}),(0,C.default)({cellCount:this.props.columnCount,cellSize:this.props.columnWidth,computeMetadataCallback:function(){return n._columnSizeAndPositionManager.resetCell(0)},computeMetadataCallbackProps:e,nextCellsCount:e.columnCount,nextCellSize:e.columnWidth,nextScrollToIndex:e.scrollToColumn,scrollToIndex:this.props.scrollToColumn,updateScrollOffsetForScrollToIndex:function(){return n._updateScrollLeftForScrollToColumn(e,t)}}),(0,C.default)({cellCount:this.props.rowCount,cellSize:this.props.rowHeight,computeMetadataCallback:function(){return n._rowSizeAndPositionManager.resetCell(0)},computeMetadataCallbackProps:e,nextCellsCount:e.rowCount,nextCellSize:e.rowHeight,nextScrollToIndex:e.scrollToRow,scrollToIndex:this.props.scrollToRow,updateScrollOffsetForScrollToIndex:function(){return n._updateScrollTopForScrollToRow(e,t)}}),this._calculateChildrenToRender(e,t)}},{key:"render",value:function(){var e=this.props,t=e.autoContainerWidth,n=e.autoHeight,o=e.className,i=e.containerStyle,l=e.height,a=e.id,s=e.noContentRenderer,u=e.style,c=e.tabIndex,d=e.width,f=this.state.isScrolling,h={boxSizing:"border-box",direction:"ltr",height:n?"auto":l,position:"relative",width:d,WebkitOverflowScrolling:"touch",willChange:"transform"},_=this._columnSizeAndPositionManager.getTotalSize(),p=this._rowSizeAndPositionManager.getTotalSize(),v=p>l?this._scrollbarSize:0,g=_>d?this._scrollbarSize:0;h.overflowX=_+v<=d?"hidden":"auto",h.overflowY=p+g<=l?"hidden":"auto";var y=this._childrenToDisplay,C=0===y.length&&l>0&&d>0;return m.default.createElement("div",{ref:this._setScrollingContainerRef,"aria-label":this.props["aria-label"],className:(0,S.default)("ReactVirtualized__Grid",o),id:a,onScroll:this._onScroll,role:"grid",style:(0,r.default)({},h,u),tabIndex:c},y.length>0&&m.default.createElement("div",{className:"ReactVirtualized__Grid__innerScrollContainer",style:(0,r.default)({width:t?"auto":_,height:p,maxWidth:_,maxHeight:p,overflow:"hidden",pointerEvents:f?"none":""},i)},y),C&&s())}},{key:"_calculateChildrenToRender",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.props,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.state,n=e.cellRenderer,o=e.cellRangeRenderer,i=e.columnCount,r=e.deferredMeasurementCache,l=e.height,a=e.overscanColumnCount,s=e.overscanRowCount,u=e.rowCount,c=e.width,d=t.isScrolling,f=t.scrollDirectionHorizontal,h=t.scrollDirectionVertical,_=t.scrollLeft,p=t.scrollTop;if(this._childrenToDisplay=[],l>0&&c>0){var v=this._columnSizeAndPositionManager.getVisibleCellRange({containerSize:c,offset:_}),m=this._rowSizeAndPositionManager.getVisibleCellRange({containerSize:l,offset:p}),g=this._columnSizeAndPositionManager.getOffsetAdjustment({containerSize:c,offset:_}),S=this._rowSizeAndPositionManager.getOffsetAdjustment({containerSize:l,offset:p});this._renderedColumnStartIndex=v.start,this._renderedColumnStopIndex=v.stop,this._renderedRowStartIndex=m.start,this._renderedRowStopIndex=m.stop;var y=(0,z.default)({cellCount:i,overscanCellsCount:a,scrollDirection:f,startIndex:this._renderedColumnStartIndex,stopIndex:this._renderedColumnStopIndex}),C=(0,z.default)({cellCount:u,overscanCellsCount:s,scrollDirection:h,startIndex:this._renderedRowStartIndex,stopIndex:this._renderedRowStopIndex});this._columnStartIndex=y.overscanStartIndex,this._columnStopIndex=y.overscanStopIndex,this._rowStartIndex=C.overscanStartIndex,this._rowStopIndex=C.overscanStopIndex,this._childrenToDisplay=o({cellCache:this._cellCache,cellRenderer:n,columnSizeAndPositionManager:this._columnSizeAndPositionManager,columnStartIndex:this._columnStartIndex,columnStopIndex:this._columnStopIndex,deferredMeasurementCache:r,horizontalOffsetAdjustment:g,isScrolling:d,parent:this,rowSizeAndPositionManager:this._rowSizeAndPositionManager,rowStartIndex:this._rowStartIndex,rowStopIndex:this._rowStopIndex,scrollLeft:_,scrollTop:p,styleCache:this._styleCache,verticalOffsetAdjustment:S,visibleColumnIndices:v,visibleRowIndices:m})}}},{key:"_debounceScrollEnded",value:function(){var e=this.props.scrollingResetTimeInterval;this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._disablePointerEventsTimeoutId=setTimeout(this._debounceScrollEndedCallback,e)}},{key:"_debounceScrollEndedCallback",value:function(){this._disablePointerEventsTimeoutId=null;var e=this._styleCache;this._cellCache={},this._styleCache={};for(var t=this._rowStartIndex;t<=this._rowStopIndex;t++)for(var n=this._columnStartIndex;n<=this._columnStopIndex;n++){var o=t+"-"+n;this._styleCache[o]=e[o]}this.setState({isScrolling:!1})}},{key:"_getEstimatedColumnSize",value:function(e){return"number"==typeof e.columnWidth?e.columnWidth:e.estimatedColumnSize}},{key:"_getEstimatedRowSize",value:function(e){return"number"==typeof e.rowHeight?e.rowHeight:e.estimatedRowSize}},{key:"_handleInvalidatedGridSize",value:function(){if("number"==typeof this._deferredInvalidateColumnIndex){var e=this._deferredInvalidateColumnIndex,t=this._deferredInvalidateRowIndex;delete this._deferredInvalidateColumnIndex,delete this._deferredInvalidateRowIndex,this.recomputeGridSize({columnIndex:e,rowIndex:t})}}},{key:"_invokeOnGridRenderedHelper",value:function(){var e=this.props.onSectionRendered;this._onGridRenderedMemoizer({callback:e,indices:{columnOverscanStartIndex:this._columnStartIndex,columnOverscanStopIndex:this._columnStopIndex,columnStartIndex:this._renderedColumnStartIndex,columnStopIndex:this._renderedColumnStopIndex,rowOverscanStartIndex:this._rowStartIndex,rowOverscanStopIndex:this._rowStopIndex,rowStartIndex:this._renderedRowStartIndex,rowStopIndex:this._renderedRowStopIndex}})}},{key:"_invokeOnScrollMemoizer",value:function(e){var t=this,n=e.scrollLeft,o=e.scrollTop,i=e.totalColumnsWidth,r=e.totalRowsHeight;this._onScrollMemoizer({callback:function(e){var n=e.scrollLeft,o=e.scrollTop,l=t.props,a=l.height,s=l.onScroll,u=l.width;s({clientHeight:a,clientWidth:u,scrollHeight:r,scrollLeft:n,scrollTop:o,scrollWidth:i})},indices:{scrollLeft:n,scrollTop:o}})}},{key:"_setScrollingContainerRef",value:function(e){this._scrollingContainer=e}},{key:"_setScrollPosition",value:function(e){var t=e.scrollLeft,n=e.scrollTop,o={scrollPositionChangeReason:A.REQUESTED};t>=0&&(o.scrollDirectionHorizontal=t>this.state.scrollLeft?T.SCROLL_DIRECTION_FORWARD:T.SCROLL_DIRECTION_BACKWARD,o.scrollLeft=t),n>=0&&(o.scrollDirectionVertical=n>this.state.scrollTop?T.SCROLL_DIRECTION_FORWARD:T.SCROLL_DIRECTION_BACKWARD,o.scrollTop=n),(t>=0&&t!==this.state.scrollLeft||n>=0&&n!==this.state.scrollTop)&&this.setState(o)}},{key:"_wrapPropertyGetter",value:function(e){return e instanceof Function?e:function(){return e}}},{key:"_wrapSizeGetter",value:function(e){return this._wrapPropertyGetter(e)}},{key:"_updateScrollLeftForScrollToColumn",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.props,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.state,n=e.columnCount,o=e.scrollToAlignment,i=e.scrollToColumn,r=e.width,l=t.scrollLeft;if(i>=0&&n>0){var a=Math.max(0,Math.min(n-1,i)),s=this._columnSizeAndPositionManager.getUpdatedOffsetForIndex({align:o,containerSize:r,currentOffset:l,targetIndex:a});l!==s&&this._setScrollPosition({scrollLeft:s})}}},{key:"_updateScrollTopForScrollToRow",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.props,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.state,n=e.height,o=e.rowCount,i=e.scrollToAlignment,r=e.scrollToRow,l=t.scrollTop;if(r>=0&&o>0){var a=Math.max(0,Math.min(o-1,r)),s=this._rowSizeAndPositionManager.getUpdatedOffsetForIndex({align:i,containerSize:n,currentOffset:l,targetIndex:a});l!==s&&this._setScrollPosition({scrollTop:s})}}},{key:"_onScroll",value:function(e){if(e.target===this._scrollingContainer&&!(e.target.scrollTop<0)){this._debounceScrollEnded();var t=this.props,n=t.autoHeight,o=t.height,i=t.width,r=this._scrollbarSize,l=this._rowSizeAndPositionManager.getTotalSize(),a=this._columnSizeAndPositionManager.getTotalSize(),s=Math.min(Math.max(0,a-i+r),e.target.scrollLeft),u=Math.min(Math.max(0,l-o+r),e.target.scrollTop);if(this.state.scrollLeft!==s||this.state.scrollTop!==u){var c=s>this.state.scrollLeft?T.SCROLL_DIRECTION_FORWARD:T.SCROLL_DIRECTION_BACKWARD,d=u>this.state.scrollTop?T.SCROLL_DIRECTION_FORWARD:T.SCROLL_DIRECTION_BACKWARD,f={isScrolling:!0,scrollDirectionHorizontal:c,scrollDirectionVertical:d,scrollLeft:s,scrollPositionChangeReason:A.OBSERVED};n||(f.scrollTop=u),this.setState(f)}this._invokeOnScrollMemoizer({scrollLeft:s,scrollTop:u,totalColumnsWidth:a,totalRowsHeight:l})}}}]),t}(v.PureComponent);G.defaultProps={"aria-label":"grid",cellRangeRenderer:L.default,estimatedColumnSize:100,estimatedRowSize:30,noContentRenderer:function(){return null},onScroll:function(){return null},onSectionRendered:function(){return null},overscanColumnCount:0,overscanRowCount:10,scrollingResetTimeInterval:E,scrollToAlignment:"auto",style:{},tabIndex:0},t.default=G},function(e,t){"use strict";function n(e){var t=e.cellCount,n=e.cellSize,o=e.computeMetadataCallback,i=e.computeMetadataCallbackProps,r=e.nextCellsCount,l=e.nextCellSize,a=e.nextScrollToIndex,s=e.scrollToIndex,u=e.updateScrollOffsetForScrollToIndex;t===r&&("number"!=typeof n&&"number"!=typeof l||n===l)||(o(i),s>=0&&s===a&&u())}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_MAX_SCROLL_SIZE=void 0;var i=n(105),r=o(i),l=n(29),a=o(l),s=n(30),u=o(s),c=n(132),d=o(c),f=t.DEFAULT_MAX_SCROLL_SIZE=15e5,h=function(){function e(t){var n=t.maxScrollSize,o=void 0===n?f:n,i=(0,r.default)(t,["maxScrollSize"]);(0,a.default)(this,e),this._cellSizeAndPositionManager=new d.default(i),this._maxScrollSize=o}return(0,u.default)(e,[{key:"areOffsetsAdjusted",value:function(){return this._cellSizeAndPositionManager.getTotalSize()>this._maxScrollSize}},{key:"configure",value:function(e){this._cellSizeAndPositionManager.configure(e)}},{key:"getCellCount",value:function(){return this._cellSizeAndPositionManager.getCellCount()}},{key:"getEstimatedCellSize",value:function(){return this._cellSizeAndPositionManager.getEstimatedCellSize()}},{key:"getLastMeasuredIndex",value:function(){return this._cellSizeAndPositionManager.getLastMeasuredIndex()}},{key:"getOffsetAdjustment",value:function(e){var t=e.containerSize,n=e.offset,o=this._cellSizeAndPositionManager.getTotalSize(),i=this.getTotalSize(),r=this._getOffsetPercentage({containerSize:t,offset:n,totalSize:i});return Math.round(r*(i-o))}},{key:"getSizeAndPositionOfCell",value:function(e){return this._cellSizeAndPositionManager.getSizeAndPositionOfCell(e)}},{key:"getSizeAndPositionOfLastMeasuredCell",value:function(){return this._cellSizeAndPositionManager.getSizeAndPositionOfLastMeasuredCell()}},{key:"getTotalSize",value:function(){return Math.min(this._maxScrollSize,this._cellSizeAndPositionManager.getTotalSize())}},{key:"getUpdatedOffsetForIndex",value:function(e){var t=e.align,n=void 0===t?"auto":t,o=e.containerSize,i=e.currentOffset,r=e.targetIndex,l=e.totalSize;i=this._safeOffsetToOffset({containerSize:o,offset:i});var a=this._cellSizeAndPositionManager.getUpdatedOffsetForIndex({align:n,containerSize:o,currentOffset:i,targetIndex:r,totalSize:l});return this._offsetToSafeOffset({containerSize:o,offset:a})}},{key:"getVisibleCellRange",value:function(e){var t=e.containerSize,n=e.offset;return n=this._safeOffsetToOffset({containerSize:t,offset:n}),this._cellSizeAndPositionManager.getVisibleCellRange({containerSize:t,offset:n})}},{key:"resetCell",value:function(e){this._cellSizeAndPositionManager.resetCell(e)}},{key:"_getOffsetPercentage",value:function(e){var t=e.containerSize,n=e.offset,o=e.totalSize;return o<=t?0:n/(o-t)}},{key:"_offsetToSafeOffset",value:function(e){var t=e.containerSize,n=e.offset,o=this._cellSizeAndPositionManager.getTotalSize(),i=this.getTotalSize();if(o===i)return n;var r=this._getOffsetPercentage({containerSize:t,offset:n,totalSize:o});return Math.round(r*(i-t))}},{key:"_safeOffsetToOffset",value:function(e){var t=e.containerSize,n=e.offset,o=this._cellSizeAndPositionManager.getTotalSize(),i=this.getTotalSize();if(o===i)return n;var r=this._getOffsetPercentage({containerSize:t,offset:n,totalSize:i});return Math.round(r*(o-t))}}]),e}();t.default=h},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(29),r=o(i),l=n(30),a=o(l),s=function(){function e(t){var n=t.batchAllCells,o=void 0!==n&&n,i=t.cellCount,l=t.cellSizeGetter,a=t.estimatedCellSize;(0,r.default)(this,e),this._batchAllCells=o,this._cellSizeGetter=l,this._cellCount=i,this._estimatedCellSize=a,this._cellSizeAndPositionData={},this._lastMeasuredIndex=-1,this._lastBatchedIndex=-1}return(0,a.default)(e,[{key:"areOffsetsAdjusted",value:function(){return!1}},{key:"configure",value:function(e){var t=e.cellCount,n=e.estimatedCellSize;this._cellCount=t,this._estimatedCellSize=n}},{key:"getCellCount",value:function(){return this._cellCount}},{key:"getEstimatedCellSize",value:function(){return this._estimatedCellSize}},{key:"getLastMeasuredIndex",value:function(){return this._lastMeasuredIndex}},{key:"getOffsetAdjustment",value:function(e){return e.containerSize,e.offset,0}},{key:"getSizeAndPositionOfCell",value:function(e){if(e<0||e>=this._cellCount)throw Error("Requested index "+e+" is outside of range 0.."+this._cellCount);if(e>this._lastMeasuredIndex)for(var t=this.getSizeAndPositionOfLastMeasuredCell(),n=t.offset+t.size,o=this._lastMeasuredIndex+1;o<=e;o++){var i=this._cellSizeGetter({index:o});if(void 0===i||isNaN(i))throw Error("Invalid size returned for cell "+o+" of value "+i);null===i?(this._cellSizeAndPositionData[o]={offset:n,size:0},this._lastBatchedIndex=e):(this._cellSizeAndPositionData[o]={offset:n,size:i},n+=i,this._lastMeasuredIndex=e)}return this._cellSizeAndPositionData[e]}},{key:"getSizeAndPositionOfLastMeasuredCell",value:function(){return this._lastMeasuredIndex>=0?this._cellSizeAndPositionData[this._lastMeasuredIndex]:{offset:0,size:0}}},{key:"getTotalSize",value:function(){var e=this.getSizeAndPositionOfLastMeasuredCell();return e.offset+e.size+(this._cellCount-this._lastMeasuredIndex-1)*this._estimatedCellSize}},{key:"getUpdatedOffsetForIndex",value:function(e){var t=e.align,n=void 0===t?"auto":t,o=e.containerSize,i=e.currentOffset,r=e.targetIndex;if(o<=0)return 0;var l=this.getSizeAndPositionOfCell(r),a=l.offset,s=a-o+l.size,u=void 0;switch(n){case"start":u=a;break;case"end":u=s;break;case"center":u=a-(o-l.size)/2;break;default:u=Math.max(s,Math.min(a,i))}var c=this.getTotalSize();return Math.max(0,Math.min(c-o,u))}},{key:"getVisibleCellRange",value:function(e){if(this._batchAllCells)return{start:0,stop:this._cellCount-1};var t=e.containerSize,n=e.offset,o=this.getTotalSize();if(0===o)return{};var i=n+t,r=this._findNearestCell(n),l=this.getSizeAndPositionOfCell(r);n=l.offset+l.size;for(var a=r;n<i&&a<this._cellCount-1;)a++,n+=this.getSizeAndPositionOfCell(a).size;return{start:r,stop:a}}},{key:"resetCell",value:function(e){this._lastMeasuredIndex=Math.min(this._lastMeasuredIndex,e-1)}},{key:"_binarySearch",value:function(e){for(var t=e.high,n=e.low,o=e.offset,i=void 0,r=void 0;n<=t;){if(i=n+Math.floor((t-n)/2),r=this.getSizeAndPositionOfCell(i).offset,r===o)return i;r<o?n=i+1:r>o&&(t=i-1)}if(n>0)return n-1}},{key:"_exponentialSearch",value:function(e){for(var t=e.index,n=e.offset,o=1;t<this._cellCount&&this.getSizeAndPositionOfCell(t).offset<n;)t+=o,o*=2;return this._binarySearch({high:Math.min(t,this._cellCount-1),low:Math.floor(t/2),offset:n})}},{key:"_findNearestCell",value:function(e){if(isNaN(e))throw Error("Invalid offset "+e+" specified");e=Math.max(0,e);var t=this.getSizeAndPositionOfLastMeasuredCell(),n=Math.max(0,this._lastMeasuredIndex);return t.offset>=e?this._binarySearch({high:n,low:0,offset:e}):this._exponentialSearch({index:n,offset:e})}}]),e}();t.default=s},function(e,t){"use strict";function n(e){var t=e.cellCount,n=e.overscanCellsCount,r=e.scrollDirection,l=e.startIndex,a=e.stopIndex,s=void 0,u=void 0;switch(r){case i:s=l,u=a+n;break;case o:s=l-n,u=a}return{overscanStartIndex:Math.max(0,s),overscanStopIndex:Math.min(t-1,u)}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n;var o=t.SCROLL_DIRECTION_BACKWARD=-1,i=t.SCROLL_DIRECTION_FORWARD=1},function(e,t){"use strict";function n(e){var t=e.cellSize,n=e.cellSizeAndPositionManager,o=e.previousCellsCount,i=e.previousCellSize,r=e.previousScrollToAlignment,l=e.previousScrollToIndex,a=e.previousSize,s=e.scrollOffset,u=e.scrollToAlignment,c=e.scrollToIndex,d=e.size,f=e.updateScrollIndexCallback,h=n.getCellCount(),_=c>=0&&c<h,p=d!==a||!i||"number"==typeof t&&t!==i;_&&(p||u!==r||c!==l)?f(c):!_&&h>0&&(d<a||h<o)&&s>n.getTotalSize()-d&&f(h-1)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,n){(function(e){"use strict";function n(t){for(var n=t.cellCache,i=t.cellRenderer,r=t.columnSizeAndPositionManager,l=t.columnStartIndex,a=t.columnStopIndex,s=t.deferredMeasurementCache,u=t.horizontalOffsetAdjustment,c=t.isScrolling,d=t.parent,f=t.rowSizeAndPositionManager,h=t.rowStartIndex,_=t.rowStopIndex,p=(t.scrollLeft,t.scrollTop,t.styleCache),v=t.verticalOffsetAdjustment,m=t.visibleColumnIndices,g=t.visibleRowIndices,S="undefined"!=typeof s,y=[],C=r.areOffsetsAdjusted()||f.areOffsetsAdjusted(),w=!c||!C,x=h;x<=_;x++)for(var R=f.getSizeAndPositionOfCell(x),b=l;b<=a;b++){var T=r.getSizeAndPositionOfCell(b),z=b>=m.start&&b<=m.stop&&x>=g.start&&x<=g.stop,M=x+"-"+b,I=void 0;w&&p[M]?I=p[M]:S&&!s.has(x,b)?I={height:"auto",left:0,position:"absolute",top:0,width:"auto"}:(I={height:R.size,left:T.offset+u,position:"absolute",top:R.offset+v,width:T.size},p[M]=I);var O={columnIndex:b,isScrolling:c,isVisible:z,key:M,parent:d,rowIndex:x,style:I},k=void 0;!c||u||v?k=i(O):(n[M]||(n[M]=i(O)),k=n[M]),null!=k&&k!==!1&&("production"!==e.env.NODE_ENV&&o(d,k),y.push(k))}return y}function o(t,n){"production"!==e.env.NODE_ENV&&n&&void 0===n.props.style&&void 0===t.__missingStyleWarning&&(t.__missingStyleWarning=!0,console.warn("Rendered cell should include style property for positioning."))}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n}).call(t,n(95))},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=e.className,n=e.columns,o=e.index,i=(e.isScrolling,e.key),r=e.onRowClick,a=e.onRowDoubleClick,u=e.onRowMouseOver,c=e.onRowMouseOut,d=e.rowData,f=e.style,h={};return(r||a||u||c)&&(h["aria-label"]="row",h.role="row",h.tabIndex=0,r&&(h.onClick=function(){return r({index:o,rowData:d})}),a&&(h.onDoubleClick=function(){return a({index:o,rowData:d})}),c&&(h.onMouseOut=function(){return c({index:o,rowData:d})}),u&&(h.onMouseOver=function(){return u({index:o,rowData:d})})),s.default.createElement("div",(0,l.default)({},h,{className:t,key:i,style:f}),n)}Object.defineProperty(t,"__esModule",{value:!0});var r=n(100),l=o(r);t.default=i;var a=n(89),s=o(a)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.InfiniteLoader=t.default=void 0;var i=n(138),r=o(i);t.default=r.default,t.InfiniteLoader=r.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=e.lastRenderedStartIndex,n=e.lastRenderedStopIndex,o=e.startIndex,i=e.stopIndex;return!(o>n||i<t)}function r(e){for(var t=e.isRowLoaded,n=e.minimumBatchSize,o=e.rowCount,i=e.startIndex,r=e.stopIndex,l=[],a=null,s=null,u=i;u<=r;u++){var c=t({index:u});c?null!==s&&(l.push({startIndex:a,stopIndex:s}),a=s=null):(s=u,null===a&&(a=u))}if(null!==s){for(var d=Math.min(Math.max(s,a+n-1),o-1),f=s+1;f<=d&&!t({index:f});f++)s=f;l.push({startIndex:a,stopIndex:s})}if(l.length)for(var h=l[0];h.stopIndex-h.startIndex+1<n&&h.startIndex>0;){var _=h.startIndex-1;if(t({index:_}))break;h.startIndex=_}return l}function l(e){var t="function"==typeof e.recomputeGridSize?e.recomputeGridSize:e.recomputeRowHeights;t?t.call(e):e.forceUpdate()}Object.defineProperty(t,"__esModule",{value:!0});var a=n(3),s=o(a),u=n(29),c=o(u),d=n(30),f=o(d),h=n(34),_=o(h),p=n(81),v=o(p);t.isRangeVisible=i,t.scanForUnloadedRanges=r,t.forceUpdateReactVirtualizedComponent=l;var m=n(89),g=n(108),S=o(g),y=function(e){function t(e,n){(0,c.default)(this,t);var o=(0,_.default)(this,(t.__proto__||(0,s.default)(t)).call(this,e,n));return o._loadMoreRowsMemoizer=(0,S.default)(),o._onRowsRendered=o._onRowsRendered.bind(o),o._registerChild=o._registerChild.bind(o),o}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){var e=this.props.children;return e({onRowsRendered:this._onRowsRendered,registerChild:this._registerChild})}},{key:"_loadUnloadedRanges",value:function(e){var t=this,n=this.props.loadMoreRows;e.forEach(function(e){var o=n(e);o&&o.then(function(){i({lastRenderedStartIndex:t._lastRenderedStartIndex,lastRenderedStopIndex:t._lastRenderedStopIndex,startIndex:e.startIndex,stopIndex:e.stopIndex})&&t._registeredChild&&l(t._registeredChild)})})}},{key:"_onRowsRendered",value:function(e){var t=this,n=e.startIndex,o=e.stopIndex,i=this.props,l=i.isRowLoaded,a=i.minimumBatchSize,s=i.rowCount,u=i.threshold;this._lastRenderedStartIndex=n,this._lastRenderedStopIndex=o;var c=r({isRowLoaded:l,minimumBatchSize:a,rowCount:s,startIndex:Math.max(0,n-u),stopIndex:Math.min(s-1,o+u)}),d=c.reduce(function(e,t){return e.concat([t.startIndex,t.stopIndex])},[]);this._loadMoreRowsMemoizer({callback:function(){t._loadUnloadedRanges(c)},indices:{squashedUnloadedRanges:d}})}},{key:"_registerChild",value:function(e){this._registeredChild=e}}]),t}(m.PureComponent);y.defaultProps={minimumBatchSize:10,rowCount:0,threshold:15},t.default=y},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.List=t.default=void 0;var i=n(140),r=o(i);t.default=r.default,t.List=r.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(141),r=o(i),l=n(105),a=o(l),s=n(100),u=o(s),c=n(3),d=o(c),f=n(29),h=o(f),_=n(30),p=o(_),v=n(34),m=o(v),g=n(81),S=o(g),y=n(128),C=o(y),w=n(89),x=o(w),R=n(107),b=o(R),T=function(e){function t(e,n){(0,h.default)(this,t);var o=(0,m.default)(this,(t.__proto__||(0,d.default)(t)).call(this,e,n));return o._cellRenderer=o._cellRenderer.bind(o),o._onScroll=o._onScroll.bind(o),o._onSectionRendered=o._onSectionRendered.bind(o),o._setRef=o._setRef.bind(o),o}return(0,S.default)(t,e),(0,p.default)(t,[{key:"forceUpdateGrid",value:function(){this.Grid.forceUpdate()}},{key:"measureAllRows",value:function(){this.Grid.measureAllCells()}},{key:"recomputeRowHeights",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.Grid.recomputeGridSize({rowIndex:e})}},{key:"scrollToRow",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.Grid.scrollToCell({columnIndex:0,rowIndex:e})}},{key:"render",value:function(){var e=this.props,t=e.className,n=e.noRowsRenderer,o=e.scrollToIndex,i=e.width,r=(0,b.default)("ReactVirtualized__List",t);return x.default.createElement(C.default,(0,u.default)({},this.props,{autoContainerWidth:!0,cellRenderer:this._cellRenderer,className:r,columnWidth:i,columnCount:1,noContentRenderer:n,onScroll:this._onScroll,onSectionRendered:this._onSectionRendered,ref:this._setRef,scrollToRow:o}))}},{key:"_cellRenderer",value:function(e){var t=e.rowIndex,n=e.style,o=(0,a.default)(e,["rowIndex","style"]),i=this.props.rowRenderer,l=(0,r.default)(n,"width"),s=l.writable;return s&&(n.width="100%"),i((0,u.default)({index:t,style:n},o))}},{key:"_setRef",value:function(e){this.Grid=e}},{key:"_onScroll",value:function(e){var t=e.clientHeight,n=e.scrollHeight,o=e.scrollTop,i=this.props.onScroll;i({clientHeight:t,scrollHeight:n,scrollTop:o})}},{key:"_onSectionRendered",value:function(e){var t=e.rowOverscanStartIndex,n=e.rowOverscanStopIndex,o=e.rowStartIndex,i=e.rowStopIndex,r=this.props.onRowsRendered;r({overscanStartIndex:t,overscanStopIndex:n,startIndex:o,stopIndex:i})}}]),t}(w.PureComponent);T.defaultProps={estimatedRowSize:30,noRowsRenderer:function(){return null},onRowsRendered:function(){return null},onScroll:function(){return null},overscanRowCount:10,scrollToAlignment:"auto",style:{}},t.default=T},function(e,t,n){e.exports={default:n(142),__esModule:!0}},function(e,t,n){n(143);var o=n(16).Object;e.exports=function(e,t){return o.getOwnPropertyDescriptor(e,t)}},function(e,t,n){var o=n(50),i=n(77).f;n(14)("getOwnPropertyDescriptor",function(){return function(e,t){return i(o(e),t)}})},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.MultiGrid=t.default=void 0;var i=n(145),r=o(i);t.default=r.default,t.MultiGrid=r.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(100),r=o(i),l=n(105),a=o(l),s=n(3),u=o(s),c=n(29),d=o(c),f=n(30),h=o(f),_=n(34),p=o(_),v=n(81),m=o(v),g=n(89),S=o(g),y=n(128),C=o(y),w=function(e){function t(e,n){(0,d.default)(this,t);var o=(0,p.default)(this,(t.__proto__||(0,u.default)(t)).call(this,e,n));return o.state={scrollLeft:0,scrollTop:0},o._bottomLeftGridRef=o._bottomLeftGridRef.bind(o),o._bottomRightGridRef=o._bottomRightGridRef.bind(o),o._cellRendererBottomLeftGrid=o._cellRendererBottomLeftGrid.bind(o),o._cellRendererBottomRightGrid=o._cellRendererBottomRightGrid.bind(o),o._cellRendererTopRightGrid=o._cellRendererTopRightGrid.bind(o),o._columnWidthRightGrid=o._columnWidthRightGrid.bind(o),o._onScroll=o._onScroll.bind(o),o._rowHeightBottomGrid=o._rowHeightBottomGrid.bind(o),o._topLeftGridRef=o._topLeftGridRef.bind(o),o._topRightGridRef=o._topRightGridRef.bind(o),o}return(0,m.default)(t,e),(0,h.default)(t,[{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:"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 e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.columnIndex,n=void 0===t?0:t,o=e.rowIndex,i=void 0===o?0:o,r=this.props,l=r.fixedColumnCount,a=r.fixedRowCount,s=Math.max(0,n-l),u=Math.max(0,i-a);this._bottomLeftGrid&&this._bottomLeftGrid.recomputeGridSize({columnIndex:n,rowIndex:u}),this._bottomRightGrid&&this._bottomRightGrid.recomputeGridSize({columnIndex:s,rowIndex:u}),this._topLeftGrid&&this._topLeftGrid.recomputeGridSize({columnIndex:n,rowIndex:i}),this._topRightGrid&&this._topRightGrid.recomputeGridSize({columnIndex:s,rowIndex:i}),this._leftGridWidth=null,this._topGridHeight=null,this._maybeCalculateCachedStyles(null,this.props)}},{key:"componentWillMount",value:function(){this._maybeCalculateCachedStyles(null,this.props)}},{key:"componentWillReceiveProps",value:function(e){var t=this.props,n=t.columnWidth,o=t.fixedColumnCount,i=t.fixedRowCount,r=t.rowHeight;n===e.columnWidth&&o===e.fixedColumnCount||(this._leftGridWidth=null),i===e.fixedRowCount&&r===e.rowHeight||(this._topGridHeight=null),this._maybeCalculateCachedStyles(this.props,e)}},{key:"render",value:function(){var e=this.props,t=e.onScroll,n=e.onSectionRendered,o=(e.scrollLeft,e.scrollToColumn),i=(e.scrollTop,
e.scrollToRow),l=(0,a.default)(e,["onScroll","onSectionRendered","scrollLeft","scrollToColumn","scrollTop","scrollToRow"]),s=this.state,u=s.scrollLeft,c=s.scrollTop;return S.default.createElement("div",{style:this._containerOuterStyle},S.default.createElement("div",{style:this._containerTopStyle},this._renderTopLeftGrid(l),this._renderTopRightGrid((0,r.default)({},l,{scrollLeft:u}))),S.default.createElement("div",{style:this._containerBottomStyle},this._renderBottomLeftGrid((0,r.default)({},l,{scrollTop:c})),this._renderBottomRightGrid((0,r.default)({},l,{onScroll:t,onSectionRendered:n,scrollLeft:u,scrollToColumn:o,scrollToRow:i,scrollTop:c}))))}},{key:"_bottomLeftGridRef",value:function(e){this._bottomLeftGrid=e}},{key:"_bottomRightGridRef",value:function(e){this._bottomRightGrid=e}},{key:"_cellRendererBottomLeftGrid",value:function(e){var t=e.rowIndex,n=(0,a.default)(e,["rowIndex"]),o=this.props,i=o.cellRenderer,l=o.fixedRowCount;return i((0,r.default)({},n,{rowIndex:t+l}))}},{key:"_cellRendererBottomRightGrid",value:function(e){var t=e.columnIndex,n=e.rowIndex,o=(0,a.default)(e,["columnIndex","rowIndex"]),i=this.props,l=i.cellRenderer,s=i.fixedColumnCount,u=i.fixedRowCount;return l((0,r.default)({},o,{columnIndex:t+s,rowIndex:n+u}))}},{key:"_cellRendererTopRightGrid",value:function(e){var t=e.columnIndex,n=(0,a.default)(e,["columnIndex"]),o=this.props,i=o.cellRenderer,l=o.fixedColumnCount;return i((0,r.default)({},n,{columnIndex:t+l}))}},{key:"_columnWidthRightGrid",value:function(e){var t=e.index,n=this.props,o=n.fixedColumnCount,i=n.columnWidth;return i instanceof Function?i({index:t+o}):i}},{key:"_getBottomGridHeight",value:function(e){var t=e.height,n=this._getTopGridHeight(e);return t-n}},{key:"_getLeftGridWidth",value:function(e){var t=e.fixedColumnCount,n=e.columnWidth;if(null==this._leftGridWidth)if(n instanceof Function){for(var o=0,i=0;i<t;i++)o+=n({index:i});this._leftGridWidth=o}else this._leftGridWidth=n*t;return this._leftGridWidth}},{key:"_getRightGridWidth",value:function(e){var t=e.width,n=this._getLeftGridWidth(e);return t-n}},{key:"_getTopGridHeight",value:function(e){var t=e.fixedRowCount,n=e.rowHeight;if(null==this._topGridHeight)if(n instanceof Function){for(var o=0,i=0;i<t;i++)o+=n({index:i});this._topGridHeight=o}else this._topGridHeight=n*t;return this._topGridHeight}},{key:"_maybeCalculateCachedStyles",value:function(e,t){var n=t.columnWidth,o=t.height,i=t.fixedColumnCount,l=t.fixedRowCount,a=t.rowHeight,s=t.style,u=t.styleBottomLeftGrid,c=t.styleBottomRightGrid,d=t.styleTopLeftGrid,f=t.styleTopRightGrid,h=t.width,_=!e,p=_||o!==e.height||h!==e.width,v=_||n!==e.columnWidth||i!==e.fixedColumnCount,m=_||l!==e.fixedRowCount||a!==e.rowHeight;(_||p||s!==e.style)&&(this._containerOuterStyle=(0,r.default)({height:o,width:h},s)),(_||p||m)&&(this._containerTopStyle={height:this._getTopGridHeight(t),position:"relative",width:h},this._containerBottomStyle={height:o-this._getTopGridHeight(t),overflow:"hidden",position:"relative",width:h}),(_||u!==e.styleBottomLeftGrid)&&(this._bottomLeftGridStyle=(0,r.default)({left:0,outline:0,overflowX:"hidden",overflowY:"hidden",position:"absolute"},u)),(_||v||c!==e.styleBottomRightGrid)&&(this._bottomRightGridStyle=(0,r.default)({left:this._getLeftGridWidth(t),outline:0,position:"absolute"},c)),(_||d!==e.styleTopLeftGrid)&&(this._topLeftGridStyle=(0,r.default)({left:0,outline:0,overflowX:"hidden",overflowY:"hidden",position:"absolute",top:0},d)),(_||v||f!==e.styleTopRightGrid)&&(this._topRightGridStyle=(0,r.default)({left:this._getLeftGridWidth(t),outline:0,overflowX:"hidden",overflowY:"hidden",position:"absolute",top:0},f))}},{key:"_onScroll",value:function(e){var t=e.scrollLeft,n=e.scrollTop;this.setState({scrollLeft:t,scrollTop:n});var o=this.props.onScroll;o&&o(e)}},{key:"_renderBottomLeftGrid",value:function(e){var t=e.fixedColumnCount,n=e.fixedRowCount,o=e.rowCount,i=e.scrollTop;return t?S.default.createElement(C.default,(0,r.default)({},e,{cellRenderer:this._cellRendererBottomLeftGrid,columnCount:t,height:this._getBottomGridHeight(e),ref:this._bottomLeftGridRef,rowCount:Math.max(0,o-n),rowHeight:this._rowHeightBottomGrid,scrollTop:i,style:this._bottomLeftGridStyle,width:this._getLeftGridWidth(e)})):null}},{key:"_renderBottomRightGrid",value:function(e){var t=e.columnCount,n=e.fixedColumnCount,o=e.fixedRowCount,i=e.rowCount,l=e.scrollToColumn,a=e.scrollToRow;return S.default.createElement(C.default,(0,r.default)({},e,{cellRenderer:this._cellRendererBottomRightGrid,columnCount:Math.max(0,t-n),columnWidth:this._columnWidthRightGrid,height:this._getBottomGridHeight(e),onScroll:this._onScroll,ref:this._bottomRightGridRef,rowCount:Math.max(0,i-o),rowHeight:this._rowHeightBottomGrid,scrollToColumn:l-n,scrollToRow:a-o,style:this._bottomRightGridStyle,width:this._getRightGridWidth(e)}))}},{key:"_renderTopLeftGrid",value:function(e){var t=e.fixedColumnCount,n=e.fixedRowCount;return t&&n?S.default.createElement(C.default,(0,r.default)({},e,{columnCount:t,height:this._getTopGridHeight(e),ref:this._topLeftGridRef,rowCount:n,style:this._topLeftGridStyle,width:this._getLeftGridWidth(e)})):null}},{key:"_renderTopRightGrid",value:function(e){var t=e.columnCount,n=e.fixedColumnCount,o=e.fixedRowCount,i=e.scrollLeft;return o?S.default.createElement(C.default,(0,r.default)({},e,{cellRenderer:this._cellRendererTopRightGrid,columnCount:Math.max(0,t-n),columnWidth:this._columnWidthRightGrid,height:this._getTopGridHeight(e),ref:this._topRightGridRef,rowCount:o,scrollLeft:i,style:this._topRightGridStyle,width:this._getRightGridWidth(e)})):null}},{key:"_rowHeightBottomGrid",value:function(e){var t=e.index,n=this.props,o=n.fixedRowCount,i=n.rowHeight;return i instanceof Function?i({index:t+o}):i}},{key:"_topLeftGridRef",value:function(e){this._topLeftGrid=e}},{key:"_topRightGridRef",value:function(e){this._topRightGrid=e}}]),t}(g.PureComponent);w.defaultProps={fixedColumnCount:0,fixedRowCount:0,style:{},styleBottomLeftGrid:{},styleBottomRightGrid:{},styleTopLeftGrid:{},styleTopRightGrid:{}},t.default=w},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollSync=t.default=void 0;var i=n(147),r=o(i);t.default=r.default,t.ScrollSync=r.default},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(3),r=o(i),l=n(29),a=o(l),s=n(30),u=o(s),c=n(34),d=o(c),f=n(81),h=o(f),_=n(89),p=function(e){function t(e,n){(0,a.default)(this,t);var o=(0,d.default)(this,(t.__proto__||(0,r.default)(t)).call(this,e,n));return o.state={clientHeight:0,clientWidth:0,scrollHeight:0,scrollLeft:0,scrollTop:0,scrollWidth:0},o._onScroll=o._onScroll.bind(o),o}return(0,h.default)(t,e),(0,u.default)(t,[{key:"render",value:function(){var e=this.props.children,t=this.state,n=t.clientHeight,o=t.clientWidth,i=t.scrollHeight,r=t.scrollLeft,l=t.scrollTop,a=t.scrollWidth;return e({clientHeight:n,clientWidth:o,onScroll:this._onScroll,scrollHeight:i,scrollLeft:r,scrollTop:l,scrollWidth:a})}},{key:"_onScroll",value:function(e){var t=e.clientHeight,n=e.clientWidth,o=e.scrollHeight,i=e.scrollLeft,r=e.scrollTop,l=e.scrollWidth;this.setState({clientHeight:t,clientWidth:n,scrollHeight:o,scrollLeft:i,scrollTop:r,scrollWidth:l})}}]),t}(_.PureComponent);t.default=p},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.IS_SCROLLING_TIMEOUT=t.WindowScroller=t.default=void 0;var i=n(149);Object.defineProperty(t,"IS_SCROLLING_TIMEOUT",{enumerable:!0,get:function(){return i.IS_SCROLLING_TIMEOUT}});var r=n(150),l=o(r);t.default=l.default,t.WindowScroller=l.default},function(e,t){"use strict";function n(){c&&(c=null,document.body.style.pointerEvents=u,u=null)}function o(){n(),s.forEach(function(e){return e.__resetIsScrolling()})}function i(){c&&clearTimeout(c),c=setTimeout(o,d)}function r(e){e.currentTarget===window&&null==u&&(u=document.body.style.pointerEvents,document.body.style.pointerEvents="none"),i(),s.forEach(function(t){t.scrollElement===e.currentTarget&&t.__handleWindowScrollEvent(e)})}function l(e,t){s.some(function(e){return e.scrollElement===t})||t.addEventListener("scroll",r),s.push(e)}function a(e,t){s=s.filter(function(t){return t!==e}),s.length||(t.removeEventListener("scroll",r),c&&(clearTimeout(c),n()))}Object.defineProperty(t,"__esModule",{value:!0}),t.registerScrollListener=l,t.unregisterScrollListener=a;var s=[],u=null,c=null,d=t.IS_SCROLLING_TIMEOUT=150},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(3),r=o(i),l=n(29),a=o(l),s=n(30),u=o(s),c=n(34),d=o(c),f=n(81),h=o(f),_=n(89),p=n(96),v=o(p),m=n(149),g=n(151),S=function(e){function t(e){(0,a.default)(this,t);var n=(0,d.default)(this,(t.__proto__||(0,r.default)(t)).call(this,e)),o="undefined"!=typeof window?(0,g.getHeight)(e.scrollElement||window):0;return n.state={height:o,isScrolling:!1,scrollTop:0},n._onResize=n._onResize.bind(n),n.__handleWindowScrollEvent=n.__handleWindowScrollEvent.bind(n),n.__resetIsScrolling=n.__resetIsScrolling.bind(n),n}return(0,h.default)(t,e),(0,u.default)(t,[{key:"updatePosition",value:function(e){var t=this.props.onResize,n=this.state.height;e=e||this.props.scrollElement||window,this._positionFromTop=(0,g.getPositionFromTop)(v.default.findDOMNode(this),e);var o=(0,g.getHeight)(e);n!==o&&(this.setState({height:o}),t({height:o}))}},{key:"componentDidMount",value:function(){var e=this.props.scrollElement||window;this.updatePosition(e),(0,m.registerScrollListener)(this,e),window.addEventListener("resize",this._onResize,!1)}},{key:"componentWillReceiveProps",value:function(e){var t=this.props.scrollElement||window,n=e.scrollElement||window;t!==n&&(this.updatePosition(n),(0,m.unregisterScrollListener)(this,t),(0,m.registerScrollListener)(this,n))}},{key:"componentWillUnmount",value:function(){(0,m.unregisterScrollListener)(this,this.props.scrollElement||window),window.removeEventListener("resize",this._onResize,!1)}},{key:"render",value:function(){var e=this.props.children,t=this.state,n=t.isScrolling,o=t.scrollTop,i=t.height;return e({height:i,isScrolling:n,scrollTop:o})}},{key:"_onResize",value:function(e){this.updatePosition()}},{key:"__handleWindowScrollEvent",value:function(e){var t=this.props.onScroll,n=this.props.scrollElement||window,o=Math.max(0,(0,g.getScrollTop)(n)-this._positionFromTop);this.setState({isScrolling:!0,scrollTop:o}),t({scrollTop:o})}},{key:"__resetIsScrolling",value:function(){this.setState({isScrolling:!1})}},{key:"scrollElement",get:function(){return this.props.scrollElement||window}}]),t}(_.PureComponent);S.defaultProps={onResize:function(){},onScroll:function(){}},t.default=S},function(e,t){"use strict";function n(e){return e===window?window.innerHeight:e.getBoundingClientRect().height}function o(e,t){var n=t===window?0:i(t),o=t===window?document.documentElement:t;return e.getBoundingClientRect().top+n-o.getBoundingClientRect().top}function i(e){return e===window?"scrollY"in window?window.scrollY:document.documentElement.scrollTop:e.scrollTop}Object.defineProperty(t,"__esModule",{value:!0}),t.getHeight=n,t.getPositionFromTop=o,t.getScrollTop=i}])});
//# sourceMappingURL=react-virtualized.min.js.map |
misc/tabledrag.js | gerrit1978/Indigov | (function ($) {
/**
* Drag and drop table rows with field manipulation.
*
* Using the drupal_add_tabledrag() function, any table with weights or parent
* relationships may be made into draggable tables. Columns containing a field
* may optionally be hidden, providing a better user experience.
*
* Created tableDrag instances may be modified with custom behaviors by
* overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods.
* See blocks.js for an example of adding additional functionality to tableDrag.
*/
Drupal.behaviors.tableDrag = {
attach: function (context, settings) {
for (var base in settings.tableDrag) {
$('#' + base, context).once('tabledrag', function () {
// Create the new tableDrag instance. Save in the Drupal variable
// to allow other scripts access to the object.
Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]);
});
}
}
};
/**
* Constructor for the tableDrag object. Provides table and field manipulation.
*
* @param table
* DOM object for the table to be made draggable.
* @param tableSettings
* Settings for the table added via drupal_add_dragtable().
*/
Drupal.tableDrag = function (table, tableSettings) {
var self = this;
// Required object variables.
this.table = table;
this.tableSettings = tableSettings;
this.dragObject = null; // Used to hold information about a current drag operation.
this.rowObject = null; // Provides operations for row manipulation.
this.oldRowElement = null; // Remember the previous element.
this.oldY = 0; // Used to determine up or down direction from last mouse move.
this.changed = false; // Whether anything in the entire table has changed.
this.maxDepth = 0; // Maximum amount of allowed parenting.
this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table.
// Configure the scroll settings.
this.scrollSettings = { amount: 4, interval: 50, trigger: 70 };
this.scrollInterval = null;
this.scrollY = 0;
this.windowHeight = 0;
// Check this table's settings to see if there are parent relationships in
// this table. For efficiency, large sections of code can be skipped if we
// don't need to track horizontal movement and indentations.
this.indentEnabled = false;
for (var group in tableSettings) {
for (var n in tableSettings[group]) {
if (tableSettings[group][n].relationship == 'parent') {
this.indentEnabled = true;
}
if (tableSettings[group][n].limit > 0) {
this.maxDepth = tableSettings[group][n].limit;
}
}
}
if (this.indentEnabled) {
this.indentCount = 1; // Total width of indents, set in makeDraggable.
// Find the width of indentations to measure mouse movements against.
// Because the table doesn't need to start with any indentations, we
// manually append 2 indentations in the first draggable row, measure
// the offset, then remove.
var indent = Drupal.theme('tableDragIndentation');
var testRow = $('<tr/>').addClass('draggable').appendTo(table);
var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent);
this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft;
testRow.remove();
}
// Make each applicable row draggable.
// Match immediate children of the parent element to allow nesting.
$('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); });
// Add a link before the table for users to show or hide weight columns.
$(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>')
.attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.'))
.click(function () {
if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
self.hideColumns();
}
else {
self.showColumns();
}
return false;
})
.wrap('<div class="tabledrag-toggle-weight-wrapper"></div>')
.parent()
);
// Initialize the specified columns (for example, weight or parent columns)
// to show or hide according to user preference. This aids accessibility
// so that, e.g., screen reader users can choose to enter weight values and
// manipulate form elements directly, rather than using drag-and-drop..
self.initColumns();
// Add mouse bindings to the document. The self variable is passed along
// as event handlers do not have direct access to the tableDrag object.
$(document).bind('mousemove', function (event) { return self.dragRow(event, self); });
$(document).bind('mouseup', function (event) { return self.dropRow(event, self); });
};
/**
* Initialize columns containing form elements to be hidden by default,
* according to the settings for this tableDrag instance.
*
* Identify and mark each cell with a CSS class so we can easily toggle
* show/hide it. Finally, hide columns if user does not have a
* 'Drupal.tableDrag.showWeight' cookie.
*/
Drupal.tableDrag.prototype.initColumns = function () {
for (var group in this.tableSettings) {
// Find the first field in this group.
for (var d in this.tableSettings[group]) {
var field = $('.' + this.tableSettings[group][d].target + ':first', this.table);
if (field.length && this.tableSettings[group][d].hidden) {
var hidden = this.tableSettings[group][d].hidden;
var cell = field.closest('td');
break;
}
}
// Mark the column containing this field so it can be hidden.
if (hidden && cell[0]) {
// Add 1 to our indexes. The nth-child selector is 1 based, not 0 based.
// Match immediate children of the parent element to allow nesting.
var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1;
$('> thead > tr, > tbody > tr, > tr', this.table).each(function () {
// Get the columnIndex and adjust for any colspans in this row.
var index = columnIndex;
var cells = $(this).children();
cells.each(function (n) {
if (n < index && this.colSpan && this.colSpan > 1) {
index -= this.colSpan - 1;
}
});
if (index > 0) {
cell = cells.filter(':nth-child(' + index + ')');
if (cell[0].colSpan && cell[0].colSpan > 1) {
// If this cell has a colspan, mark it so we can reduce the colspan.
cell.addClass('tabledrag-has-colspan');
}
else {
// Mark this cell so we can hide it.
cell.addClass('tabledrag-hide');
}
}
});
}
}
// Now hide cells and reduce colspans unless cookie indicates previous choice.
// Set a cookie if it is not already present.
if ($.cookie('Drupal.tableDrag.showWeight') === null) {
$.cookie('Drupal.tableDrag.showWeight', 0, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
this.hideColumns();
}
// Check cookie value and show/hide weight columns accordingly.
else {
if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
this.showColumns();
}
else {
this.hideColumns();
}
}
};
/**
* Hide the columns containing weight/parent form elements.
* Undo showColumns().
*/
Drupal.tableDrag.prototype.hideColumns = function () {
// Hide weight/parent cells and headers.
$('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none');
// Show TableDrag handles.
$('.tabledrag-handle', 'table.tabledrag-processed').css('display', '');
// Reduce the colspan of any effected multi-span columns.
$('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
this.colSpan = this.colSpan - 1;
});
// Change link text.
$('.tabledrag-toggle-weight').text(Drupal.t('Show row weights'));
// Change cookie.
$.cookie('Drupal.tableDrag.showWeight', 0, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
// Trigger an event to allow other scripts to react to this display change.
$('table.tabledrag-processed').trigger('columnschange', 'hide');
};
/**
* Show the columns containing weight/parent form elements
* Undo hideColumns().
*/
Drupal.tableDrag.prototype.showColumns = function () {
// Show weight/parent cells and headers.
$('.tabledrag-hide', 'table.tabledrag-processed').css('display', '');
// Hide TableDrag handles.
$('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none');
// Increase the colspan for any columns where it was previously reduced.
$('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
this.colSpan = this.colSpan + 1;
});
// Change link text.
$('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights'));
// Change cookie.
$.cookie('Drupal.tableDrag.showWeight', 1, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
// Trigger an event to allow other scripts to react to this display change.
$('table.tabledrag-processed').trigger('columnschange', 'show');
};
/**
* Find the target used within a particular row and group.
*/
Drupal.tableDrag.prototype.rowSettings = function (group, row) {
var field = $('.' + group, row);
for (var delta in this.tableSettings[group]) {
var targetClass = this.tableSettings[group][delta].target;
if (field.is('.' + targetClass)) {
// Return a copy of the row settings.
var rowSettings = {};
for (var n in this.tableSettings[group][delta]) {
rowSettings[n] = this.tableSettings[group][delta][n];
}
return rowSettings;
}
}
};
/**
* Take an item and add event handlers to make it become draggable.
*/
Drupal.tableDrag.prototype.makeDraggable = function (item) {
var self = this;
// Create the handle.
var handle = $('<a href="#" class="tabledrag-handle"><div class="handle"> </div></a>').attr('title', Drupal.t('Drag to re-order'));
// Insert the handle after indentations (if any).
if ($('td:first .indentation:last', item).length) {
$('td:first .indentation:last', item).after(handle);
// Update the total width of indentation in this entire table.
self.indentCount = Math.max($('.indentation', item).length, self.indentCount);
}
else {
$('td:first', item).prepend(handle);
}
// Add hover action for the handle.
handle.hover(function () {
self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null;
}, function () {
self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null;
});
// Add the mousedown action for the handle.
handle.mousedown(function (event) {
// Create a new dragObject recording the event information.
self.dragObject = {};
self.dragObject.initMouseOffset = self.getMouseOffset(item, event);
self.dragObject.initMouseCoords = self.mouseCoords(event);
if (self.indentEnabled) {
self.dragObject.indentMousePos = self.dragObject.initMouseCoords;
}
// If there's a lingering row object from the keyboard, remove its focus.
if (self.rowObject) {
$('a.tabledrag-handle', self.rowObject.element).blur();
}
// Create a new rowObject for manipulation of this row.
self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true);
// Save the position of the table.
self.table.topY = $(self.table).offset().top;
self.table.bottomY = self.table.topY + self.table.offsetHeight;
// Add classes to the handle and row.
$(this).addClass('tabledrag-handle-hover');
$(item).addClass('drag');
// Set the document to use the move cursor during drag.
$('body').addClass('drag');
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'none');
}
// Hack for Konqueror, prevent the blur handler from firing.
// Konqueror always gives links focus, even after returning false on mousedown.
self.safeBlur = false;
// Call optional placeholder function.
self.onDrag();
return false;
});
// Prevent the anchor tag from jumping us to the top of the page.
handle.click(function () {
return false;
});
// Similar to the hover event, add a class when the handle is focused.
handle.focus(function () {
$(this).addClass('tabledrag-handle-hover');
self.safeBlur = true;
});
// Remove the handle class on blur and fire the same function as a mouseup.
handle.blur(function (event) {
$(this).removeClass('tabledrag-handle-hover');
if (self.rowObject && self.safeBlur) {
self.dropRow(event, self);
}
});
// Add arrow-key support to the handle.
handle.keydown(function (event) {
// If a rowObject doesn't yet exist and this isn't the tab key.
if (event.keyCode != 9 && !self.rowObject) {
self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true);
}
var keyChange = false;
switch (event.keyCode) {
case 37: // Left arrow.
case 63234: // Safari left arrow.
keyChange = true;
self.rowObject.indent(-1 * self.rtl);
break;
case 38: // Up arrow.
case 63232: // Safari up arrow.
var previousRow = $(self.rowObject.element).prev('tr').get(0);
while (previousRow && $(previousRow).is(':hidden')) {
previousRow = $(previousRow).prev('tr').get(0);
}
if (previousRow) {
self.safeBlur = false; // Do not allow the onBlur cleanup.
self.rowObject.direction = 'up';
keyChange = true;
if ($(item).is('.tabledrag-root')) {
// Swap with the previous top-level row.
var groupHeight = 0;
while (previousRow && $('.indentation', previousRow).length) {
previousRow = $(previousRow).prev('tr').get(0);
groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight;
}
if (previousRow) {
self.rowObject.swap('before', previousRow);
// No need to check for indentation, 0 is the only valid one.
window.scrollBy(0, -groupHeight);
}
}
else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) {
// Swap with the previous row (unless previous row is the first one
// and undraggable).
self.rowObject.swap('before', previousRow);
self.rowObject.interval = null;
self.rowObject.indent(0);
window.scrollBy(0, -parseInt(item.offsetHeight, 10));
}
handle.get(0).focus(); // Regain focus after the DOM manipulation.
}
break;
case 39: // Right arrow.
case 63235: // Safari right arrow.
keyChange = true;
self.rowObject.indent(1 * self.rtl);
break;
case 40: // Down arrow.
case 63233: // Safari down arrow.
var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0);
while (nextRow && $(nextRow).is(':hidden')) {
nextRow = $(nextRow).next('tr').get(0);
}
if (nextRow) {
self.safeBlur = false; // Do not allow the onBlur cleanup.
self.rowObject.direction = 'down';
keyChange = true;
if ($(item).is('.tabledrag-root')) {
// Swap with the next group (necessarily a top-level one).
var groupHeight = 0;
var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false);
if (nextGroup) {
$(nextGroup.group).each(function () {
groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight;
});
var nextGroupRow = $(nextGroup.group).filter(':last').get(0);
self.rowObject.swap('after', nextGroupRow);
// No need to check for indentation, 0 is the only valid one.
window.scrollBy(0, parseInt(groupHeight, 10));
}
}
else {
// Swap with the next row.
self.rowObject.swap('after', nextRow);
self.rowObject.interval = null;
self.rowObject.indent(0);
window.scrollBy(0, parseInt(item.offsetHeight, 10));
}
handle.get(0).focus(); // Regain focus after the DOM manipulation.
}
break;
}
if (self.rowObject && self.rowObject.changed == true) {
$(item).addClass('drag');
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
self.oldRowElement = item;
self.restripeTable();
self.onDrag();
}
// Returning false if we have an arrow key to prevent scrolling.
if (keyChange) {
return false;
}
});
// Compatibility addition, return false on keypress to prevent unwanted scrolling.
// IE and Safari will suppress scrolling on keydown, but all other browsers
// need to return false on keypress. http://www.quirksmode.org/js/keys.html
handle.keypress(function (event) {
switch (event.keyCode) {
case 37: // Left arrow.
case 38: // Up arrow.
case 39: // Right arrow.
case 40: // Down arrow.
return false;
}
});
};
/**
* Mousemove event handler, bound to document.
*/
Drupal.tableDrag.prototype.dragRow = function (event, self) {
if (self.dragObject) {
self.currentMouseCoords = self.mouseCoords(event);
var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y;
var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x;
// Check for row swapping and vertical scrolling.
if (y != self.oldY) {
self.rowObject.direction = y > self.oldY ? 'down' : 'up';
self.oldY = y; // Update the old value.
// Check if the window should be scrolled (and how fast).
var scrollAmount = self.checkScroll(self.currentMouseCoords.y);
// Stop any current scrolling.
clearInterval(self.scrollInterval);
// Continue scrolling if the mouse has moved in the scroll direction.
if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') {
self.setScroll(scrollAmount);
}
// If we have a valid target, perform the swap and restripe the table.
var currentRow = self.findDropTargetRow(x, y);
if (currentRow) {
if (self.rowObject.direction == 'down') {
self.rowObject.swap('after', currentRow, self);
}
else {
self.rowObject.swap('before', currentRow, self);
}
self.restripeTable();
}
}
// Similar to row swapping, handle indentations.
if (self.indentEnabled) {
var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x;
// Set the number of indentations the mouse has been moved left or right.
var indentDiff = Math.round(xDiff / self.indentAmount * self.rtl);
// Indent the row with our estimated diff, which may be further
// restricted according to the rows around this row.
var indentChange = self.rowObject.indent(indentDiff);
// Update table and mouse indentations.
self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl;
self.indentCount = Math.max(self.indentCount, self.rowObject.indents);
}
return false;
}
};
/**
* Mouseup event handler, bound to document.
* Blur event handler, bound to drag handle for keyboard support.
*/
Drupal.tableDrag.prototype.dropRow = function (event, self) {
// Drop row functionality shared between mouseup and blur events.
if (self.rowObject != null) {
var droppedRow = self.rowObject.element;
// The row is already in the right place so we just release it.
if (self.rowObject.changed == true) {
// Update the fields in the dropped row.
self.updateFields(droppedRow);
// If a setting exists for affecting the entire group, update all the
// fields in the entire dragged group.
for (var group in self.tableSettings) {
var rowSettings = self.rowSettings(group, droppedRow);
if (rowSettings.relationship == 'group') {
for (var n in self.rowObject.children) {
self.updateField(self.rowObject.children[n], group);
}
}
}
self.rowObject.markChanged();
if (self.changed == false) {
$(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');
self.changed = true;
}
}
if (self.indentEnabled) {
self.rowObject.removeIndentClasses();
}
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
$(droppedRow).removeClass('drag').addClass('drag-previous');
self.oldRowElement = droppedRow;
self.onDrop();
self.rowObject = null;
}
// Functionality specific only to mouseup event.
if (self.dragObject != null) {
$('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover');
self.dragObject = null;
$('body').removeClass('drag');
clearInterval(self.scrollInterval);
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'block');
}
}
};
/**
* Get the mouse coordinates from the event (allowing for browser differences).
*/
Drupal.tableDrag.prototype.mouseCoords = function (event) {
if (event.pageX || event.pageY) {
return { x: event.pageX, y: event.pageY };
}
return {
x: event.clientX + document.body.scrollLeft - document.body.clientLeft,
y: event.clientY + document.body.scrollTop - document.body.clientTop
};
};
/**
* Given a target element and a mouse event, get the mouse offset from that
* element. To do this we need the element's position and the mouse position.
*/
Drupal.tableDrag.prototype.getMouseOffset = function (target, event) {
var docPos = $(target).offset();
var mousePos = this.mouseCoords(event);
return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top };
};
/**
* Find the row the mouse is currently over. This row is then taken and swapped
* with the one being dragged.
*
* @param x
* The x coordinate of the mouse on the page (not the screen).
* @param y
* The y coordinate of the mouse on the page (not the screen).
*/
Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) {
var rows = $(this.table.tBodies[0].rows).not(':hidden');
for (var n = 0; n < rows.length; n++) {
var row = rows[n];
var indentDiff = 0;
var rowY = $(row).offset().top;
// Because Safari does not report offsetHeight on table rows, but does on
// table cells, grab the firstChild of the row and use that instead.
// http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari.
if (row.offsetHeight == 0) {
var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2;
}
// Other browsers.
else {
var rowHeight = parseInt(row.offsetHeight, 10) / 2;
}
// Because we always insert before, we need to offset the height a bit.
if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) {
if (this.indentEnabled) {
// Check that this row is not a child of the row being dragged.
for (var n in this.rowObject.group) {
if (this.rowObject.group[n] == row) {
return null;
}
}
}
else {
// Do not allow a row to be swapped with itself.
if (row == this.rowObject.element) {
return null;
}
}
// Check that swapping with this row is allowed.
if (!this.rowObject.isValidSwap(row)) {
return null;
}
// We may have found the row the mouse just passed over, but it doesn't
// take into account hidden rows. Skip backwards until we find a draggable
// row.
while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) {
row = $(row).prev('tr').get(0);
}
return row;
}
}
return null;
};
/**
* After the row is dropped, update the table fields according to the settings
* set for this table.
*
* @param changedRow
* DOM object for the row that was just dropped.
*/
Drupal.tableDrag.prototype.updateFields = function (changedRow) {
for (var group in this.tableSettings) {
// Each group may have a different setting for relationship, so we find
// the source rows for each separately.
this.updateField(changedRow, group);
}
};
/**
* After the row is dropped, update a single table field according to specific
* settings.
*
* @param changedRow
* DOM object for the row that was just dropped.
* @param group
* The settings group on which field updates will occur.
*/
Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
var rowSettings = this.rowSettings(group, changedRow);
// Set the row as its own target.
if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') {
var sourceRow = changedRow;
}
// Siblings are easy, check previous and next rows.
else if (rowSettings.relationship == 'sibling') {
var previousRow = $(changedRow).prev('tr').get(0);
var nextRow = $(changedRow).next('tr').get(0);
var sourceRow = changedRow;
if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) {
if (this.indentEnabled) {
if ($('.indentations', previousRow).length == $('.indentations', changedRow)) {
sourceRow = previousRow;
}
}
else {
sourceRow = previousRow;
}
}
else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) {
if (this.indentEnabled) {
if ($('.indentations', nextRow).length == $('.indentations', changedRow)) {
sourceRow = nextRow;
}
}
else {
sourceRow = nextRow;
}
}
}
// Parents, look up the tree until we find a field not in this group.
// Go up as many parents as indentations in the changed row.
else if (rowSettings.relationship == 'parent') {
var previousRow = $(changedRow).prev('tr');
while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) {
previousRow = previousRow.prev('tr');
}
// If we found a row.
if (previousRow.length) {
sourceRow = previousRow[0];
}
// Otherwise we went all the way to the left of the table without finding
// a parent, meaning this item has been placed at the root level.
else {
// Use the first row in the table as source, because it's guaranteed to
// be at the root level. Find the first item, then compare this row
// against it as a sibling.
sourceRow = $(this.table).find('tr.draggable:first').get(0);
if (sourceRow == this.rowObject.element) {
sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
}
var useSibling = true;
}
}
// Because we may have moved the row from one category to another,
// take a look at our sibling and borrow its sources and targets.
this.copyDragClasses(sourceRow, changedRow, group);
rowSettings = this.rowSettings(group, changedRow);
// In the case that we're looking for a parent, but the row is at the top
// of the tree, copy our sibling's values.
if (useSibling) {
rowSettings.relationship = 'sibling';
rowSettings.source = rowSettings.target;
}
var targetClass = '.' + rowSettings.target;
var targetElement = $(targetClass, changedRow).get(0);
// Check if a target element exists in this row.
if (targetElement) {
var sourceClass = '.' + rowSettings.source;
var sourceElement = $(sourceClass, sourceRow).get(0);
switch (rowSettings.action) {
case 'depth':
// Get the depth of the target row.
targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length;
break;
case 'match':
// Update the value.
targetElement.value = sourceElement.value;
break;
case 'order':
var siblings = this.rowObject.findSiblings(rowSettings);
if ($(targetElement).is('select')) {
// Get a list of acceptable values.
var values = [];
$('option', targetElement).each(function () {
values.push(this.value);
});
var maxVal = values[values.length - 1];
// Populate the values in the siblings.
$(targetClass, siblings).each(function () {
// If there are more items than possible values, assign the maximum value to the row.
if (values.length > 0) {
this.value = values.shift();
}
else {
this.value = maxVal;
}
});
}
else {
// Assume a numeric input field.
var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0;
$(targetClass, siblings).each(function () {
this.value = weight;
weight++;
});
}
break;
}
}
};
/**
* Copy all special tableDrag classes from one row's form elements to a
* different one, removing any special classes that the destination row
* may have had.
*/
Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) {
var sourceElement = $('.' + group, sourceRow);
var targetElement = $('.' + group, targetRow);
if (sourceElement.length && targetElement.length) {
targetElement[0].className = sourceElement[0].className;
}
};
Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
var de = document.documentElement;
var b = document.body;
var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight);
var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY));
var trigger = this.scrollSettings.trigger;
var delta = 0;
// Return a scroll speed relative to the edge of the screen.
if (cursorY - scrollY > windowHeight - trigger) {
delta = trigger / (windowHeight + scrollY - cursorY);
delta = (delta > 0 && delta < trigger) ? delta : trigger;
return delta * this.scrollSettings.amount;
}
else if (cursorY - scrollY < trigger) {
delta = trigger / (cursorY - scrollY);
delta = (delta > 0 && delta < trigger) ? delta : trigger;
return -delta * this.scrollSettings.amount;
}
};
Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
var self = this;
this.scrollInterval = setInterval(function () {
// Update the scroll values stored in the object.
self.checkScroll(self.currentMouseCoords.y);
var aboveTable = self.scrollY > self.table.topY;
var belowTable = self.scrollY + self.windowHeight < self.table.bottomY;
if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) {
window.scrollBy(0, scrollAmount);
}
}, this.scrollSettings.interval);
};
Drupal.tableDrag.prototype.restripeTable = function () {
// :even and :odd are reversed because jQuery counts from 0 and
// we count from 1, so we're out of sync.
// Match immediate children of the parent element to allow nesting.
$('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table)
.removeClass('odd even')
.filter(':odd').addClass('even').end()
.filter(':even').addClass('odd');
};
/**
* Stub function. Allows a custom handler when a row begins dragging.
*/
Drupal.tableDrag.prototype.onDrag = function () {
return null;
};
/**
* Stub function. Allows a custom handler when a row is dropped.
*/
Drupal.tableDrag.prototype.onDrop = function () {
return null;
};
/**
* Constructor to make a new object to manipulate a table row.
*
* @param tableRow
* The DOM element for the table row we will be manipulating.
* @param method
* The method in which this row is being moved. Either 'keyboard' or 'mouse'.
* @param indentEnabled
* Whether the containing table uses indentations. Used for optimizations.
* @param maxDepth
* The maximum amount of indentations this row may contain.
* @param addClasses
* Whether we want to add classes to this row to indicate child relationships.
*/
Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
this.element = tableRow;
this.method = method;
this.group = [tableRow];
this.groupDepth = $('.indentation', tableRow).length;
this.changed = false;
this.table = $(tableRow).closest('table').get(0);
this.indentEnabled = indentEnabled;
this.maxDepth = maxDepth;
this.direction = ''; // Direction the row is being moved.
if (this.indentEnabled) {
this.indents = $('.indentation', tableRow).length;
this.children = this.findChildren(addClasses);
this.group = $.merge(this.group, this.children);
// Find the depth of this entire group.
for (var n = 0; n < this.group.length; n++) {
this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth);
}
}
};
/**
* Find all children of rowObject by indentation.
*
* @param addClasses
* Whether we want to add classes to this row to indicate child relationships.
*/
Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
var parentIndentation = this.indents;
var currentRow = $(this.element, this.table).next('tr.draggable');
var rows = [];
var child = 0;
while (currentRow.length) {
var rowIndentation = $('.indentation', currentRow).length;
// A greater indentation indicates this is a child.
if (rowIndentation > parentIndentation) {
child++;
rows.push(currentRow[0]);
if (addClasses) {
$('.indentation', currentRow).each(function (indentNum) {
if (child == 1 && (indentNum == parentIndentation)) {
$(this).addClass('tree-child-first');
}
if (indentNum == parentIndentation) {
$(this).addClass('tree-child');
}
else if (indentNum > parentIndentation) {
$(this).addClass('tree-child-horizontal');
}
});
}
}
else {
break;
}
currentRow = currentRow.next('tr.draggable');
}
if (addClasses && rows.length) {
$('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last');
}
return rows;
};
/**
* Ensure that two rows are allowed to be swapped.
*
* @param row
* DOM object for the row being considered for swapping.
*/
Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
if (this.indentEnabled) {
var prevRow, nextRow;
if (this.direction == 'down') {
prevRow = row;
nextRow = $(row).next('tr').get(0);
}
else {
prevRow = $(row).prev('tr').get(0);
nextRow = row;
}
this.interval = this.validIndentInterval(prevRow, nextRow);
// We have an invalid swap if the valid indentations interval is empty.
if (this.interval.min > this.interval.max) {
return false;
}
}
// Do not let an un-draggable first row have anything put before it.
if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) {
return false;
}
return true;
};
/**
* Perform the swap between two rows.
*
* @param position
* Whether the swap will occur 'before' or 'after' the given row.
* @param row
* DOM element what will be swapped with the row group.
*/
Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) {
Drupal.detachBehaviors(this.group, Drupal.settings, 'move');
$(row)[position](this.group);
Drupal.attachBehaviors(this.group, Drupal.settings);
this.changed = true;
this.onSwap(row);
};
/**
* Determine the valid indentations interval for the row at a given position
* in the table.
*
* @param prevRow
* DOM object for the row before the tested position
* (or null for first position in the table).
* @param nextRow
* DOM object for the row after the tested position
* (or null for last position in the table).
*/
Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) {
var minIndent, maxIndent;
// Minimum indentation:
// Do not orphan the next row.
minIndent = nextRow ? $('.indentation', nextRow).length : 0;
// Maximum indentation:
if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) {
// Do not indent:
// - the first row in the table,
// - rows dragged below a non-draggable row,
// - 'root' rows.
maxIndent = 0;
}
else {
// Do not go deeper than as a child of the previous row.
maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1);
// Limit by the maximum allowed depth for the table.
if (this.maxDepth) {
maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents));
}
}
return { 'min': minIndent, 'max': maxIndent };
};
/**
* Indent a row within the legal bounds of the table.
*
* @param indentDiff
* The number of additional indentations proposed for the row (can be
* positive or negative). This number will be adjusted to nearest valid
* indentation level for the row.
*/
Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) {
// Determine the valid indentations interval if not available yet.
if (!this.interval) {
var prevRow = $(this.element).prev('tr').get(0);
var nextRow = $(this.group).filter(':last').next('tr').get(0);
this.interval = this.validIndentInterval(prevRow, nextRow);
}
// Adjust to the nearest valid indentation.
var indent = this.indents + indentDiff;
indent = Math.max(indent, this.interval.min);
indent = Math.min(indent, this.interval.max);
indentDiff = indent - this.indents;
for (var n = 1; n <= Math.abs(indentDiff); n++) {
// Add or remove indentations.
if (indentDiff < 0) {
$('.indentation:first', this.group).remove();
this.indents--;
}
else {
$('td:first', this.group).prepend(Drupal.theme('tableDragIndentation'));
this.indents++;
}
}
if (indentDiff) {
// Update indentation for this row.
this.changed = true;
this.groupDepth += indentDiff;
this.onIndent();
}
return indentDiff;
};
/**
* Find all siblings for a row, either according to its subgroup or indentation.
* Note that the passed-in row is included in the list of siblings.
*
* @param settings
* The field settings we're using to identify what constitutes a sibling.
*/
Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) {
var siblings = [];
var directions = ['prev', 'next'];
var rowIndentation = this.indents;
for (var d = 0; d < directions.length; d++) {
var checkRow = $(this.element)[directions[d]]();
while (checkRow.length) {
// Check that the sibling contains a similar target field.
if ($('.' + rowSettings.target, checkRow)) {
// Either add immediately if this is a flat table, or check to ensure
// that this row has the same level of indentation.
if (this.indentEnabled) {
var checkRowIndentation = $('.indentation', checkRow).length;
}
if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) {
siblings.push(checkRow[0]);
}
else if (checkRowIndentation < rowIndentation) {
// No need to keep looking for siblings when we get to a parent.
break;
}
}
else {
break;
}
checkRow = $(checkRow)[directions[d]]();
}
// Since siblings are added in reverse order for previous, reverse the
// completed list of previous siblings. Add the current row and continue.
if (directions[d] == 'prev') {
siblings.reverse();
siblings.push(this.element);
}
}
return siblings;
};
/**
* Remove indentation helper classes from the current row group.
*/
Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () {
for (var n in this.children) {
$('.indentation', this.children[n])
.removeClass('tree-child')
.removeClass('tree-child-first')
.removeClass('tree-child-last')
.removeClass('tree-child-horizontal');
}
};
/**
* Add an asterisk or other marker to the changed row.
*/
Drupal.tableDrag.prototype.row.prototype.markChanged = function () {
var marker = Drupal.theme('tableDragChangedMarker');
var cell = $('td:first', this.element);
if ($('span.tabledrag-changed', cell).length == 0) {
cell.append(marker);
}
};
/**
* Stub function. Allows a custom handler when a row is indented.
*/
Drupal.tableDrag.prototype.row.prototype.onIndent = function () {
return null;
};
/**
* Stub function. Allows a custom handler when a row is swapped.
*/
Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
return null;
};
Drupal.theme.prototype.tableDragChangedMarker = function () {
return '<span class="warning tabledrag-changed">*</span>';
};
Drupal.theme.prototype.tableDragIndentation = function () {
return '<div class="indentation"> </div>';
};
Drupal.theme.prototype.tableDragChangedWarning = function () {
return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>';
};
})(jQuery);
|
packages/material-ui-icons/src/FormatShapes.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M23 7V1h-6v2H7V1H1v6h2v10H1v6h6v-2h10v2h6v-6h-2V7h2zM3 3h2v2H3V3zm2 18H3v-2h2v2zm12-2H7v-2H5V7h2V5h10v2h2v10h-2v2zm4 2h-2v-2h2v2zM19 5V3h2v2h-2zm-5.27 9h-3.49l-.73 2H7.89l3.4-9h1.4l3.41 9h-1.63l-.74-2zm-3.04-1.26h2.61L12 8.91l-1.31 3.83z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment>
, 'FormatShapes');
|
webpack/routes/OvalPolicies/OvalPoliciesShow/DetailsTab.js | theforeman/foreman_openscap | import React from 'react';
import PropTypes from 'prop-types';
import { useMutation } from '@apollo/client';
import {
TextList,
TextContent,
TextArea,
TextListItem,
TextListVariants,
TextListItemVariants,
TextInput,
} from '@patternfly/react-core';
import { translate as __ } from 'foremanReact/common/I18n';
import EditableInput from '../../../components/EditableInput';
import { onAttrUpdate, policySchedule } from './OvalPoliciesShowHelper';
import updateOvalPolicyMutation from '../../../graphql/mutations/updateOvalPolicy.gql';
const DetailsTab = props => {
const { policy, showToast } = props;
const [callMutation] = useMutation(updateOvalPolicyMutation);
return (
<TextContent className="pf-u-pt-md">
<TextList component={TextListVariants.dl}>
<TextListItem component={TextListItemVariants.dt}>
{__('Name')}
</TextListItem>
<TextListItem
aria-label="label text value"
component={TextListItemVariants.dd}
className="foreman-spaced-list"
>
<EditableInput
value={policy.name}
onConfirm={onAttrUpdate('name', policy, callMutation, showToast)}
component={TextInput}
attrName="name"
allowed={policy.meta.canEdit}
/>
</TextListItem>
<TextListItem component={TextListItemVariants.dt}>
{__('Period')}
</TextListItem>
<TextListItem
aria-label="label text value"
component={TextListItemVariants.dd}
className="foreman-spaced-list"
>
{policySchedule(policy)}
</TextListItem>
<TextListItem component={TextListItemVariants.dt}>
{__('Description')}
</TextListItem>
<TextListItem
aria-label="label text value"
component={TextListItemVariants.dd}
className="foreman-spaced-list"
>
<EditableInput
value={policy.description}
onConfirm={onAttrUpdate(
'description',
policy,
callMutation,
showToast
)}
component={TextArea}
attrName="description"
allowed={policy.meta.canEdit}
/>
</TextListItem>
</TextList>
</TextContent>
);
};
DetailsTab.propTypes = {
policy: PropTypes.object.isRequired,
showToast: PropTypes.func.isRequired,
};
export default DetailsTab;
|
docs/src/routes/contact/Contact.js | bmatthews/haze-lea | /**
* 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 PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Contact.css';
class Contact extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>
{this.props.title}
</h1>
<p>...</p>
</div>
</div>
);
}
}
export default withStyles(s)(Contact);
|
styleguide/sections/Type.js | scott-riley/loggins | import React, { Component } from 'react';
import Section from '../components/Section';
import SectionTitle from 'components/SectionTitle/SectionTitle';
import * as t from 'globals/typography.css';
export default class Type extends Component {
render() {
return (
<Section name="Typography" href="https://github.com/PactCoffee/loggins/blob/master/styleguide/sections/Type.js">
<p>
We use two typefaces throughout the site: Brandon Grotesque and Lunchbox Slab. Instead of arbitrarily using any font anywhere, we use specific type styles for specific use cases:
</p>
<h1 className={t.hero}>Hero heading</h1>
<h1 className={t.primary}>Primary heading</h1>
<h1 className={t.sub}>Sub heading</h1>
<h1 className={t.title}>Title</h1>
<SectionTitle>Section Title</SectionTitle>
<SectionTitle>Really very long section title indeed</SectionTitle>
<p>Body text is always brandon. We have <em>italic</em> and <strong>bold</strong>, as well as light, thin, medium and black weights (to be used specifically).</p>
</Section>
);
}
}
|
src/js/components/icons/base/Stop.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-stop`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'stop');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><rect width="16" height="16" x="4" y="4" fill="none" stroke="#000" strokeWidth="2"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Stop';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
client/auth/Error.js | bryanph/Geist | import React from 'react'
export const ValidationErrors = (props) => {
const errors = props.errors
if (!errors) {
return <noscipt />
}
const fields = Object.keys(errors)
if (!fields.length) {
return <noscript />
}
const errorList = fields.map(field => (
<li>invalid field {field}: {errors[field]}</li>
))
return (
<div className="panel error">
<h5>Errors were found!</h5>
<ul>
{ errorList }
</ul>
</div>
)
}
export const RenderErrors = (props) => {
const errors = props.errors
if (!errors || !errors.length) {
return <noscript />
}
let errorList = errors.map(error => (
<li>{error}</li>
))
return (
<ul>
{errorList}
</ul>
)
}
|
test/components/MainSection.spec.js | thetallweeks/react-redux-es6-istanbul-starter-kit | import expect from 'expect'
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import MainSection from '../../src/components/MainSection'
import TodoItem from '../../src/components/TodoItem'
import Footer from '../../src/components/Footer'
import { SHOW_ALL, SHOW_COMPLETED } from '../../src/constants/TodoFilters'
function setup(propOverrides) {
const props = Object.assign({
todos: [
{
text: 'Use Redux',
completed: false,
id: 0
}, {
text: 'Run the tests',
completed: true,
id: 1
}
],
actions: {
editTodo: expect.createSpy(),
deleteTodo: expect.createSpy(),
completeTodo: expect.createSpy(),
completeAll: expect.createSpy(),
clearCompleted: expect.createSpy()
}
}, propOverrides)
const renderer = TestUtils.createRenderer()
renderer.render(<MainSection {...props} />)
const output = renderer.getRenderOutput()
return {
props: props,
output: output,
renderer: renderer
}
}
describe('components', () => {
describe('MainSection', () => {
it('should render container', () => {
const { output } = setup()
expect(output.type).toBe('section')
expect(output.props.className).toBe('main')
})
describe('toggle all input', () => {
it('should render', () => {
const { output } = setup()
const [ toggle ] = output.props.children
expect(toggle.type).toBe('input')
expect(toggle.props.type).toBe('checkbox')
expect(toggle.props.checked).toBe(false)
})
it('should be checked if all todos completed', () => {
const { output } = setup({ todos: [
{
text: 'Use Redux',
completed: true,
id: 0
}
]
})
const [ toggle ] = output.props.children
expect(toggle.props.checked).toBe(true)
})
it('should call completeAll on change', () => {
const { output, props } = setup()
const [ toggle ] = output.props.children
toggle.props.onChange({})
expect(props.actions.completeAll).toHaveBeenCalled()
})
})
describe('footer', () => {
it('should render', () => {
const { output } = setup()
const [ , , footer ] = output.props.children
expect(footer.type).toBe(Footer)
expect(footer.props.completedCount).toBe(1)
expect(footer.props.activeCount).toBe(1)
expect(footer.props.filter).toBe(SHOW_ALL)
})
it('onShow should set the filter', () => {
const { output, renderer } = setup()
const [ , , footer ] = output.props.children
footer.props.onShow(SHOW_COMPLETED)
const updated = renderer.getRenderOutput()
const [ , , updatedFooter ] = updated.props.children
expect(updatedFooter.props.filter).toBe(SHOW_COMPLETED)
})
it('onClearCompleted should call clearCompleted', () => {
const { output, props } = setup()
const [ , , footer ] = output.props.children
footer.props.onClearCompleted()
expect(props.actions.clearCompleted).toHaveBeenCalled()
})
})
describe('todo list', () => {
it('should render', () => {
const { output, props } = setup()
const [ , list ] = output.props.children
expect(list.type).toBe('ul')
expect(list.props.children.length).toBe(2)
list.props.children.forEach((item, i) => {
expect(item.type).toBe(TodoItem)
expect(item.props.todo).toBe(props.todos[i])
})
})
it('should filter items', () => {
const { output, renderer, props } = setup()
const [ , , footer ] = output.props.children
footer.props.onShow(SHOW_COMPLETED)
const updated = renderer.getRenderOutput()
const [ , updatedList ] = updated.props.children
expect(updatedList.props.children.length).toBe(1)
expect(updatedList.props.children[0].props.todo).toBe(props.todos[1])
})
})
})
})
|
ajax/libs/react-slick/0.14.0/react-slick.js | dc-js/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["Slider"] = factory(require("react"), require("react-dom"));
else
root["Slider"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_6__) {
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 _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _innerSlider = __webpack_require__(3);
var _objectAssign = __webpack_require__(7);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _json2mq = __webpack_require__(15);
var _json2mq2 = _interopRequireDefault(_json2mq);
var _reactResponsiveMixin = __webpack_require__(17);
var _reactResponsiveMixin2 = _interopRequireDefault(_reactResponsiveMixin);
var _defaultProps = __webpack_require__(10);
var _defaultProps2 = _interopRequireDefault(_defaultProps);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Slider = _react2.default.createClass({
displayName: 'Slider',
mixins: [_reactResponsiveMixin2.default],
innerSlider: null,
innerSliderRefHandler: function innerSliderRefHandler(ref) {
this.innerSlider = ref;
},
getInitialState: function getInitialState() {
return {
breakpoint: null
};
},
componentWillMount: function componentWillMount() {
var _this = this;
if (this.props.responsive) {
var breakpoints = this.props.responsive.map(function (breakpt) {
return breakpt.breakpoint;
});
breakpoints.sort(function (x, y) {
return x - y;
});
breakpoints.forEach(function (breakpoint, index) {
var bQuery;
if (index === 0) {
bQuery = (0, _json2mq2.default)({ minWidth: 0, maxWidth: breakpoint });
} else {
bQuery = (0, _json2mq2.default)({ minWidth: breakpoints[index - 1], maxWidth: breakpoint });
}
_this.media(bQuery, function () {
_this.setState({ breakpoint: breakpoint });
});
});
// Register media query for full screen. Need to support resize from small to large
var query = (0, _json2mq2.default)({ minWidth: breakpoints.slice(-1)[0] });
this.media(query, function () {
_this.setState({ breakpoint: null });
});
}
},
slickPrev: function slickPrev() {
this.innerSlider.slickPrev();
},
slickNext: function slickNext() {
this.innerSlider.slickNext();
},
slickGoTo: function slickGoTo(slide) {
this.innerSlider.slickGoTo(slide);
},
render: function render() {
var _this2 = this;
var settings;
var newProps;
if (this.state.breakpoint) {
newProps = this.props.responsive.filter(function (resp) {
return resp.breakpoint === _this2.state.breakpoint;
});
settings = newProps[0].settings === 'unslick' ? 'unslick' : (0, _objectAssign2.default)({}, this.props, newProps[0].settings);
} else {
settings = (0, _objectAssign2.default)({}, _defaultProps2.default, this.props);
}
var children = this.props.children;
if (!Array.isArray(children)) {
children = [children];
}
// Children may contain false or null, so we should filter them
children = children.filter(function (child) {
return !!child;
});
if (settings === 'unslick') {
// if 'unslick' responsive breakpoint setting used, just return the <Slider> tag nested HTML
return _react2.default.createElement(
'div',
null,
children
);
} else {
return _react2.default.createElement(
_innerSlider.InnerSlider,
_extends({ ref: this.innerSliderRefHandler }, settings),
children
);
}
}
});
module.exports = Slider;
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.InnerSlider = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _eventHandlers = __webpack_require__(4);
var _eventHandlers2 = _interopRequireDefault(_eventHandlers);
var _helpers = __webpack_require__(8);
var _helpers2 = _interopRequireDefault(_helpers);
var _initialState = __webpack_require__(9);
var _initialState2 = _interopRequireDefault(_initialState);
var _defaultProps = __webpack_require__(10);
var _defaultProps2 = _interopRequireDefault(_defaultProps);
var _classnames = __webpack_require__(11);
var _classnames2 = _interopRequireDefault(_classnames);
var _objectAssign = __webpack_require__(7);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _track = __webpack_require__(12);
var _dots = __webpack_require__(13);
var _arrows = __webpack_require__(14);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var InnerSlider = exports.InnerSlider = _react2.default.createClass({
displayName: 'InnerSlider',
mixins: [_helpers2.default, _eventHandlers2.default],
list: null,
track: null,
listRefHandler: function listRefHandler(ref) {
this.list = ref;
},
trackRefHandler: function trackRefHandler(ref) {
this.track = ref;
},
getInitialState: function getInitialState() {
return _extends({}, _initialState2.default, {
currentSlide: this.props.initialSlide
});
},
getDefaultProps: function getDefaultProps() {
return _defaultProps2.default;
},
componentWillMount: function componentWillMount() {
if (this.props.init) {
this.props.init();
}
this.setState({
mounted: true
});
var lazyLoadedList = [];
for (var i = 0; i < _react2.default.Children.count(this.props.children); i++) {
if (i >= this.state.currentSlide && i < this.state.currentSlide + this.props.slidesToShow) {
lazyLoadedList.push(i);
}
}
if (this.props.lazyLoad && this.state.lazyLoadedList.length === 0) {
this.setState({
lazyLoadedList: lazyLoadedList
});
}
},
componentDidMount: function componentDidMount() {
// Hack for autoplay -- Inspect Later
this.initialize(this.props);
this.adaptHeight();
// To support server-side rendering
if (!window) {
return;
}
if (window.addEventListener) {
window.addEventListener('resize', this.onWindowResized);
} else {
window.attachEvent('onresize', this.onWindowResized);
}
},
componentWillUnmount: function componentWillUnmount() {
if (this.animationEndCallback) {
clearTimeout(this.animationEndCallback);
}
if (window.addEventListener) {
window.removeEventListener('resize', this.onWindowResized);
} else {
window.detachEvent('onresize', this.onWindowResized);
}
if (this.state.autoPlayTimer) {
clearInterval(this.state.autoPlayTimer);
}
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (this.props.slickGoTo != nextProps.slickGoTo) {
if ((undefined) !== 'production') {
console.warn('react-slick deprecation warning: slickGoTo prop is deprecated and it will be removed in next release. Use slickGoTo method instead');
}
this.changeSlide({
message: 'index',
index: nextProps.slickGoTo,
currentSlide: this.state.currentSlide
});
} else if (this.state.currentSlide >= nextProps.children.length) {
this.update(nextProps);
this.changeSlide({
message: 'index',
index: nextProps.children.length - nextProps.slidesToShow,
currentSlide: this.state.currentSlide
});
} else {
this.update(nextProps);
}
},
componentDidUpdate: function componentDidUpdate() {
this.adaptHeight();
},
onWindowResized: function onWindowResized() {
this.update(this.props);
// animating state should be cleared while resizing, otherwise autoplay stops working
this.setState({
animating: false
});
},
slickPrev: function slickPrev() {
this.changeSlide({ message: 'previous' });
},
slickNext: function slickNext() {
this.changeSlide({ message: 'next' });
},
slickGoTo: function slickGoTo(slide) {
typeof slide === 'number' && this.changeSlide({
message: 'index',
index: slide,
currentSlide: this.state.currentSlide
});
},
render: function render() {
var className = (0, _classnames2.default)('slick-initialized', 'slick-slider', this.props.className, {
'slick-vertical': this.props.vertical
});
var trackProps = {
fade: this.props.fade,
cssEase: this.props.cssEase,
speed: this.props.speed,
infinite: this.props.infinite,
centerMode: this.props.centerMode,
focusOnSelect: this.props.focusOnSelect ? this.selectHandler : null,
currentSlide: this.state.currentSlide,
lazyLoad: this.props.lazyLoad,
lazyLoadedList: this.state.lazyLoadedList,
rtl: this.props.rtl,
slideWidth: this.state.slideWidth,
slidesToShow: this.props.slidesToShow,
slidesToScroll: this.props.slidesToScroll,
slideCount: this.state.slideCount,
trackStyle: this.state.trackStyle,
variableWidth: this.props.variableWidth
};
var dots;
if (this.props.dots === true && this.state.slideCount >= this.props.slidesToShow) {
var dotProps = {
dotsClass: this.props.dotsClass,
slideCount: this.state.slideCount,
slidesToShow: this.props.slidesToShow,
currentSlide: this.state.currentSlide,
slidesToScroll: this.props.slidesToScroll,
clickHandler: this.changeSlide
};
dots = _react2.default.createElement(_dots.Dots, dotProps);
}
var prevArrow, nextArrow;
var arrowProps = {
infinite: this.props.infinite,
centerMode: this.props.centerMode,
currentSlide: this.state.currentSlide,
slideCount: this.state.slideCount,
slidesToShow: this.props.slidesToShow,
prevArrow: this.props.prevArrow,
nextArrow: this.props.nextArrow,
clickHandler: this.changeSlide
};
if (this.props.arrows) {
prevArrow = _react2.default.createElement(_arrows.PrevArrow, arrowProps);
nextArrow = _react2.default.createElement(_arrows.NextArrow, arrowProps);
}
var verticalHeightStyle = null;
if (this.props.vertical) {
verticalHeightStyle = {
height: this.state.listHeight
};
}
var centerPaddingStyle = null;
if (this.props.vertical === false) {
if (this.props.centerMode === true) {
centerPaddingStyle = {
padding: '0px ' + this.props.centerPadding
};
}
} else {
if (this.props.centerMode === true) {
centerPaddingStyle = {
padding: this.props.centerPadding + ' 0px'
};
}
}
var listStyle = (0, _objectAssign2.default)({}, verticalHeightStyle, centerPaddingStyle);
return _react2.default.createElement(
'div',
{ className: className, onMouseEnter: this.onInnerSliderEnter, onMouseLeave: this.onInnerSliderLeave },
prevArrow,
_react2.default.createElement(
'div',
{
ref: this.listRefHandler,
className: 'slick-list',
style: listStyle,
onMouseDown: this.swipeStart,
onMouseMove: this.state.dragging ? this.swipeMove : null,
onMouseUp: this.swipeEnd,
onMouseLeave: this.state.dragging ? this.swipeEnd : null,
onTouchStart: this.swipeStart,
onTouchMove: this.state.dragging ? this.swipeMove : null,
onTouchEnd: this.swipeEnd,
onTouchCancel: this.state.dragging ? this.swipeEnd : null,
onKeyDown: this.props.accessibility ? this.keyHandler : null },
_react2.default.createElement(
_track.Track,
_extends({ ref: this.trackRefHandler }, trackProps),
this.props.children
)
),
nextArrow,
dots
);
}
});
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _trackHelper = __webpack_require__(5);
var _helpers = __webpack_require__(8);
var _helpers2 = _interopRequireDefault(_helpers);
var _objectAssign = __webpack_require__(7);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var EventHandlers = {
// Event handler for previous and next
changeSlide: function changeSlide(options) {
var indexOffset, previousInt, slideOffset, unevenOffset, targetSlide;
var _props = this.props;
var slidesToScroll = _props.slidesToScroll;
var slidesToShow = _props.slidesToShow;
var _state = this.state;
var slideCount = _state.slideCount;
var currentSlide = _state.currentSlide;
unevenOffset = slideCount % slidesToScroll !== 0;
indexOffset = unevenOffset ? 0 : (slideCount - currentSlide) % slidesToScroll;
if (options.message === 'previous') {
slideOffset = indexOffset === 0 ? slidesToScroll : slidesToShow - indexOffset;
targetSlide = currentSlide - slideOffset;
if (this.props.lazyLoad) {
previousInt = currentSlide - slideOffset;
targetSlide = previousInt === -1 ? slideCount - 1 : previousInt;
}
} else if (options.message === 'next') {
slideOffset = indexOffset === 0 ? slidesToScroll : indexOffset;
targetSlide = currentSlide + slideOffset;
if (this.props.lazyLoad) {
targetSlide = (currentSlide + slidesToScroll) % slideCount + indexOffset;
}
} else if (options.message === 'dots' || options.message === 'children') {
// Click on dots
targetSlide = options.index * options.slidesToScroll;
if (targetSlide === options.currentSlide) {
return;
}
} else if (options.message === 'index') {
targetSlide = parseInt(options.index);
if (targetSlide === options.currentSlide) {
return;
}
}
this.slideHandler(targetSlide);
},
// Accessiblity handler for previous and next
keyHandler: function keyHandler(e) {
//Dont slide if the cursor is inside the form fields and arrow keys are pressed
if (!e.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
if (e.keyCode === 37 && this.props.accessibility === true) {
this.changeSlide({
message: this.props.rtl === true ? 'next' : 'previous'
});
} else if (e.keyCode === 39 && this.props.accessibility === true) {
this.changeSlide({
message: this.props.rtl === true ? 'previous' : 'next'
});
}
}
},
// Focus on selecting a slide (click handler on track)
selectHandler: function selectHandler(options) {
this.changeSlide(options);
},
swipeStart: function swipeStart(e) {
var touches, posX, posY;
if (this.props.swipe === false || 'ontouchend' in document && this.props.swipe === false) {
return;
} else if (this.props.draggable === false && e.type.indexOf('mouse') !== -1) {
return;
}
posX = e.touches !== undefined ? e.touches[0].pageX : e.clientX;
posY = e.touches !== undefined ? e.touches[0].pageY : e.clientY;
this.setState({
dragging: true,
touchObject: {
startX: posX,
startY: posY,
curX: posX,
curY: posY
}
});
},
swipeMove: function swipeMove(e) {
if (!this.state.dragging) {
e.preventDefault();
return;
}
if (this.state.animating) {
return;
}
var swipeLeft;
var curLeft, positionOffset;
var touchObject = this.state.touchObject;
curLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({
slideIndex: this.state.currentSlide,
trackRef: this.track
}, this.props, this.state));
touchObject.curX = e.touches ? e.touches[0].pageX : e.clientX;
touchObject.curY = e.touches ? e.touches[0].pageY : e.clientY;
touchObject.swipeLength = Math.round(Math.sqrt(Math.pow(touchObject.curX - touchObject.startX, 2)));
if (this.props.verticalSwiping) {
touchObject.swipeLength = Math.round(Math.sqrt(Math.pow(touchObject.curY - touchObject.startY, 2)));
}
positionOffset = (this.props.rtl === false ? 1 : -1) * (touchObject.curX > touchObject.startX ? 1 : -1);
if (this.props.verticalSwiping) {
positionOffset = touchObject.curY > touchObject.startY ? 1 : -1;
}
var currentSlide = this.state.currentSlide;
var dotCount = Math.ceil(this.state.slideCount / this.props.slidesToScroll);
var swipeDirection = this.swipeDirection(this.state.touchObject);
var touchSwipeLength = touchObject.swipeLength;
if (this.props.infinite === false) {
if (currentSlide === 0 && swipeDirection === 'right' || currentSlide + 1 >= dotCount && swipeDirection === 'left') {
touchSwipeLength = touchObject.swipeLength * this.props.edgeFriction;
if (this.state.edgeDragged === false && this.props.edgeEvent) {
this.props.edgeEvent(swipeDirection);
this.setState({ edgeDragged: true });
}
}
}
if (this.state.swiped === false && this.props.swipeEvent) {
this.props.swipeEvent(swipeDirection);
this.setState({ swiped: true });
}
if (!this.props.vertical) {
swipeLeft = curLeft + touchSwipeLength * positionOffset;
} else {
swipeLeft = curLeft + touchSwipeLength * (this.state.listHeight / this.state.listWidth) * positionOffset;
}
if (this.props.verticalSwiping) {
swipeLeft = curLeft + touchSwipeLength * positionOffset;
}
this.setState({
touchObject: touchObject,
swipeLeft: swipeLeft,
trackStyle: (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: swipeLeft }, this.props, this.state))
});
if (Math.abs(touchObject.curX - touchObject.startX) < Math.abs(touchObject.curY - touchObject.startY) * 0.8) {
return;
}
if (touchObject.swipeLength > 4) {
e.preventDefault();
}
},
swipeEnd: function swipeEnd(e) {
if (!this.state.dragging) {
e.preventDefault();
return;
}
var touchObject = this.state.touchObject;
var minSwipe = this.state.listWidth / this.props.touchThreshold;
var swipeDirection = this.swipeDirection(touchObject);
if (this.props.verticalSwiping) {
minSwipe = this.state.listHeight / this.props.touchThreshold;
}
// reset the state of touch related state variables.
this.setState({
dragging: false,
edgeDragged: false,
swiped: false,
swipeLeft: null,
touchObject: {}
});
// Fix for #13
if (!touchObject.swipeLength) {
return;
}
if (touchObject.swipeLength > minSwipe) {
e.preventDefault();
switch (swipeDirection) {
case 'left':
case 'down':
this.slideHandler(this.state.currentSlide + this.props.slidesToScroll);
break;
case 'right':
case 'up':
this.slideHandler(this.state.currentSlide - this.props.slidesToScroll);
break;
default:
}
} else {
// Adjust the track back to it's original position.
var currentLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({
slideIndex: this.state.currentSlide,
trackRef: this.track
}, this.props, this.state));
this.setState({
trackStyle: (0, _trackHelper.getTrackAnimateCSS)((0, _objectAssign2.default)({ left: currentLeft }, this.props, this.state))
});
}
},
onInnerSliderEnter: function onInnerSliderEnter(e) {
if (this.props.autoplay && this.props.pauseOnHover) {
this.pause();
}
},
onInnerSliderLeave: function onInnerSliderLeave(e) {
if (this.props.autoplay && this.props.pauseOnHover) {
this.autoPlay();
}
}
};
exports.default = EventHandlers;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.getTrackLeft = exports.getTrackAnimateCSS = exports.getTrackCSS = undefined;
var _reactDom = __webpack_require__(6);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _objectAssign = __webpack_require__(7);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var checkSpecKeys = function checkSpecKeys(spec, keysArray) {
return keysArray.reduce(function (value, key) {
return value && spec.hasOwnProperty(key);
}, true) ? null : console.error('Keys Missing', spec);
};
var getTrackCSS = exports.getTrackCSS = function getTrackCSS(spec) {
checkSpecKeys(spec, ['left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth']);
var trackWidth, trackHeight;
var trackChildren = spec.slideCount + 2 * spec.slidesToShow;
if (!spec.vertical) {
if (spec.variableWidth) {
trackWidth = (spec.slideCount + 2 * spec.slidesToShow) * spec.slideWidth;
} else if (spec.centerMode) {
trackWidth = (spec.slideCount + 2 * (spec.slidesToShow + 1)) * spec.slideWidth;
} else {
trackWidth = (spec.slideCount + 2 * spec.slidesToShow) * spec.slideWidth;
}
} else {
trackHeight = trackChildren * spec.slideHeight;
}
var style = {
opacity: 1,
WebkitTransform: !spec.vertical ? 'translate3d(' + spec.left + 'px, 0px, 0px)' : 'translate3d(0px, ' + spec.left + 'px, 0px)',
transform: !spec.vertical ? 'translate3d(' + spec.left + 'px, 0px, 0px)' : 'translate3d(0px, ' + spec.left + 'px, 0px)',
transition: '',
WebkitTransition: '',
msTransform: !spec.vertical ? 'translateX(' + spec.left + 'px)' : 'translateY(' + spec.left + 'px)'
};
if (trackWidth) {
(0, _objectAssign2.default)(style, { width: trackWidth });
}
if (trackHeight) {
(0, _objectAssign2.default)(style, { height: trackHeight });
}
// Fallback for IE8
if (window && !window.addEventListener && window.attachEvent) {
if (!spec.vertical) {
style.marginLeft = spec.left + 'px';
} else {
style.marginTop = spec.left + 'px';
}
}
return style;
};
var getTrackAnimateCSS = exports.getTrackAnimateCSS = function getTrackAnimateCSS(spec) {
checkSpecKeys(spec, ['left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth', 'speed', 'cssEase']);
var style = getTrackCSS(spec);
// useCSS is true by default so it can be undefined
style.WebkitTransition = '-webkit-transform ' + spec.speed + 'ms ' + spec.cssEase;
style.transition = 'transform ' + spec.speed + 'ms ' + spec.cssEase;
return style;
};
var getTrackLeft = exports.getTrackLeft = function getTrackLeft(spec) {
checkSpecKeys(spec, ['slideIndex', 'trackRef', 'infinite', 'centerMode', 'slideCount', 'slidesToShow', 'slidesToScroll', 'slideWidth', 'listWidth', 'variableWidth', 'slideHeight']);
var slideOffset = 0;
var targetLeft;
var targetSlide;
var verticalOffset = 0;
if (spec.fade) {
return 0;
}
if (spec.infinite) {
if (spec.slideCount >= spec.slidesToShow) {
slideOffset = spec.slideWidth * spec.slidesToShow * -1;
verticalOffset = spec.slideHeight * spec.slidesToShow * -1;
}
if (spec.slideCount % spec.slidesToScroll !== 0) {
if (spec.slideIndex + spec.slidesToScroll > spec.slideCount && spec.slideCount > spec.slidesToShow) {
if (spec.slideIndex > spec.slideCount) {
slideOffset = (spec.slidesToShow - (spec.slideIndex - spec.slideCount)) * spec.slideWidth * -1;
verticalOffset = (spec.slidesToShow - (spec.slideIndex - spec.slideCount)) * spec.slideHeight * -1;
} else {
slideOffset = spec.slideCount % spec.slidesToScroll * spec.slideWidth * -1;
verticalOffset = spec.slideCount % spec.slidesToScroll * spec.slideHeight * -1;
}
}
}
} else {
if (spec.slideCount % spec.slidesToScroll !== 0) {
if (spec.slideIndex + spec.slidesToScroll > spec.slideCount && spec.slideCount > spec.slidesToShow) {
var slidesToOffset = spec.slidesToShow - spec.slideCount % spec.slidesToScroll;
slideOffset = slidesToOffset * spec.slideWidth;
}
}
}
if (spec.centerMode) {
if (spec.infinite) {
slideOffset += spec.slideWidth * Math.floor(spec.slidesToShow / 2);
} else {
slideOffset = spec.slideWidth * Math.floor(spec.slidesToShow / 2);
}
}
if (!spec.vertical) {
targetLeft = spec.slideIndex * spec.slideWidth * -1 + slideOffset;
} else {
targetLeft = spec.slideIndex * spec.slideHeight * -1 + verticalOffset;
}
if (spec.variableWidth === true) {
var targetSlideIndex;
if (spec.slideCount <= spec.slidesToShow || spec.infinite === false) {
targetSlide = _reactDom2.default.findDOMNode(spec.trackRef).childNodes[spec.slideIndex];
} else {
targetSlideIndex = spec.slideIndex + spec.slidesToShow;
targetSlide = _reactDom2.default.findDOMNode(spec.trackRef).childNodes[targetSlideIndex];
}
targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0;
if (spec.centerMode === true) {
if (spec.infinite === false) {
targetSlide = _reactDom2.default.findDOMNode(spec.trackRef).children[spec.slideIndex];
} else {
targetSlide = _reactDom2.default.findDOMNode(spec.trackRef).children[spec.slideIndex + spec.slidesToShow + 1];
}
targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0;
targetLeft += (spec.listWidth - targetSlide.offsetWidth) / 2;
}
}
return targetLeft;
};
/***/ },
/* 6 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_6__;
/***/ },
/* 7 */
/***/ function(module, exports) {
'use strict';
/* eslint-disable no-unused-vars */
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
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 (e) {
// 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 (Object.getOwnPropertySymbols) {
symbols = Object.getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(6);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _trackHelper = __webpack_require__(5);
var _objectAssign = __webpack_require__(7);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var helpers = {
initialize: function initialize(props) {
var slickList = _reactDom2.default.findDOMNode(this.list);
var slideCount = _react2.default.Children.count(props.children);
var listWidth = this.getWidth(slickList);
var trackWidth = this.getWidth(_reactDom2.default.findDOMNode(this.track));
var slideWidth;
if (!props.vertical) {
slideWidth = trackWidth / props.slidesToShow;
} else {
slideWidth = trackWidth;
}
var slideHeight = this.getHeight(slickList.querySelector('[data-index="0"]'));
var listHeight = slideHeight * props.slidesToShow;
var currentSlide = props.rtl ? slideCount - 1 - props.initialSlide : props.initialSlide;
this.setState({
slideCount: slideCount,
slideWidth: slideWidth,
listWidth: listWidth,
trackWidth: trackWidth,
currentSlide: currentSlide,
slideHeight: slideHeight,
listHeight: listHeight
}, function () {
var targetLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({
slideIndex: this.state.currentSlide,
trackRef: this.track
}, props, this.state));
// getCSS function needs previously set state
var trackStyle = (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: targetLeft }, props, this.state));
this.setState({ trackStyle: trackStyle });
this.autoPlay(); // once we're set up, trigger the initial autoplay.
});
},
update: function update(props) {
var slickList = _reactDom2.default.findDOMNode(this.list);
// This method has mostly same code as initialize method.
// Refactor it
var slideCount = _react2.default.Children.count(props.children);
var listWidth = this.getWidth(slickList);
var trackWidth = this.getWidth(_reactDom2.default.findDOMNode(this.track));
var slideWidth;
if (!props.vertical) {
slideWidth = trackWidth / props.slidesToShow;
} else {
slideWidth = trackWidth;
}
var slideHeight = this.getHeight(slickList.querySelector('[data-index="0"]'));
var listHeight = slideHeight * props.slidesToShow;
// pause slider if autoplay is set to false
if (!props.autoplay) this.pause();
this.setState({
slideCount: slideCount,
slideWidth: slideWidth,
listWidth: listWidth,
trackWidth: trackWidth,
slideHeight: slideHeight,
listHeight: listHeight
}, function () {
var targetLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({
slideIndex: this.state.currentSlide,
trackRef: this.track
}, props, this.state));
// getCSS function needs previously set state
var trackStyle = (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: targetLeft }, props, this.state));
this.setState({ trackStyle: trackStyle });
});
},
getWidth: function getWidth(elem) {
return elem.getBoundingClientRect().width || elem.offsetWidth;
},
getHeight: function getHeight(elem) {
return elem.getBoundingClientRect().height || elem.offsetHeight;
},
adaptHeight: function adaptHeight() {
if (this.props.adaptiveHeight) {
var selector = '[data-index="' + this.state.currentSlide + '"]';
if (this.list) {
var slickList = _reactDom2.default.findDOMNode(this.list);
slickList.style.height = slickList.querySelector(selector).offsetHeight + 'px';
}
}
},
slideHandler: function slideHandler(index) {
var _this = this;
// Functionality of animateSlide and postSlide is merged into this function
// console.log('slideHandler', index);
var targetSlide, currentSlide;
var targetLeft, currentLeft;
var callback;
if (this.props.waitForAnimate && this.state.animating) {
return;
}
if (this.props.fade) {
currentSlide = this.state.currentSlide;
// Don't change slide if it's not infite and current slide is the first or last slide.
if (this.props.infinite === false && (index < 0 || index >= this.state.slideCount)) {
return;
}
// Shifting targetSlide back into the range
if (index < 0) {
targetSlide = index + this.state.slideCount;
} else if (index >= this.state.slideCount) {
targetSlide = index - this.state.slideCount;
} else {
targetSlide = index;
}
if (this.props.lazyLoad && this.state.lazyLoadedList.indexOf(targetSlide) < 0) {
this.setState({
lazyLoadedList: this.state.lazyLoadedList.concat(targetSlide)
});
}
callback = function callback() {
_this.setState({
animating: false
});
if (_this.props.afterChange) {
_this.props.afterChange(targetSlide);
}
delete _this.animationEndCallback;
};
this.setState({
animating: true,
currentSlide: targetSlide
}, function () {
this.animationEndCallback = setTimeout(callback, this.props.speed);
});
if (this.props.beforeChange) {
this.props.beforeChange(this.state.currentSlide, targetSlide);
}
this.autoPlay();
return;
}
targetSlide = index;
if (targetSlide < 0) {
if (this.props.infinite === false) {
currentSlide = 0;
} else if (this.state.slideCount % this.props.slidesToScroll !== 0) {
currentSlide = this.state.slideCount - this.state.slideCount % this.props.slidesToScroll;
} else {
currentSlide = this.state.slideCount + targetSlide;
}
} else if (targetSlide >= this.state.slideCount) {
if (this.props.infinite === false) {
currentSlide = this.state.slideCount - this.props.slidesToShow;
} else if (this.state.slideCount % this.props.slidesToScroll !== 0) {
currentSlide = 0;
} else {
currentSlide = targetSlide - this.state.slideCount;
}
} else {
currentSlide = targetSlide;
}
targetLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({
slideIndex: targetSlide,
trackRef: this.track
}, this.props, this.state));
currentLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({
slideIndex: currentSlide,
trackRef: this.track
}, this.props, this.state));
if (this.props.infinite === false) {
targetLeft = currentLeft;
}
if (this.props.beforeChange) {
this.props.beforeChange(this.state.currentSlide, currentSlide);
}
if (this.props.lazyLoad) {
var loaded = true;
var slidesToLoad = [];
for (var i = targetSlide; i < targetSlide + this.props.slidesToShow; i++) {
loaded = loaded && this.state.lazyLoadedList.indexOf(i) >= 0;
if (!loaded) {
slidesToLoad.push(i);
}
}
if (!loaded) {
this.setState({
lazyLoadedList: this.state.lazyLoadedList.concat(slidesToLoad)
});
}
}
// Slide Transition happens here.
// animated transition happens to target Slide and
// non - animated transition happens to current Slide
// If CSS transitions are false, directly go the current slide.
if (this.props.useCSS === false) {
this.setState({
currentSlide: currentSlide,
trackStyle: (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: currentLeft }, this.props, this.state))
}, function () {
if (this.props.afterChange) {
this.props.afterChange(currentSlide);
}
});
} else {
var nextStateChanges = {
animating: false,
currentSlide: currentSlide,
trackStyle: (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: currentLeft }, this.props, this.state)),
swipeLeft: null
};
callback = function callback() {
_this.setState(nextStateChanges);
if (_this.props.afterChange) {
_this.props.afterChange(currentSlide);
}
delete _this.animationEndCallback;
};
this.setState({
animating: true,
currentSlide: currentSlide,
trackStyle: (0, _trackHelper.getTrackAnimateCSS)((0, _objectAssign2.default)({ left: targetLeft }, this.props, this.state))
}, function () {
this.animationEndCallback = setTimeout(callback, this.props.speed);
});
}
this.autoPlay();
},
swipeDirection: function swipeDirection(touchObject) {
var xDist, yDist, r, swipeAngle;
xDist = touchObject.startX - touchObject.curX;
yDist = touchObject.startY - touchObject.curY;
r = Math.atan2(yDist, xDist);
swipeAngle = Math.round(r * 180 / Math.PI);
if (swipeAngle < 0) {
swipeAngle = 360 - Math.abs(swipeAngle);
}
if (swipeAngle <= 45 && swipeAngle >= 0 || swipeAngle <= 360 && swipeAngle >= 315) {
return this.props.rtl === false ? 'left' : 'right';
}
if (swipeAngle >= 135 && swipeAngle <= 225) {
return this.props.rtl === false ? 'right' : 'left';
}
if (this.props.verticalSwiping === true) {
if (swipeAngle >= 35 && swipeAngle <= 135) {
return 'down';
} else {
return 'up';
}
}
return 'vertical';
},
autoPlay: function autoPlay() {
var _this2 = this;
if (this.state.autoPlayTimer) {
return;
}
var play = function play() {
if (_this2.state.mounted) {
var nextIndex = _this2.props.rtl ? _this2.state.currentSlide - _this2.props.slidesToScroll : _this2.state.currentSlide + _this2.props.slidesToScroll;
_this2.slideHandler(nextIndex);
}
};
if (this.props.autoplay) {
this.setState({
autoPlayTimer: setInterval(play, this.props.autoplaySpeed)
});
}
},
pause: function pause() {
if (this.state.autoPlayTimer) {
clearInterval(this.state.autoPlayTimer);
this.setState({
autoPlayTimer: null
});
}
}
};
exports.default = helpers;
/***/ },
/* 9 */
/***/ function(module, exports) {
"use strict";
var initialState = {
animating: false,
dragging: false,
autoPlayTimer: null,
currentDirection: 0,
currentLeft: null,
currentSlide: 0,
direction: 1,
listWidth: null,
listHeight: null,
// loadIndex: 0,
slideCount: null,
slideWidth: null,
slideHeight: null,
// sliding: false,
// slideOffset: 0,
swipeLeft: null,
touchObject: {
startX: 0,
startY: 0,
curX: 0,
curY: 0
},
lazyLoadedList: [],
// added for react
initialized: false,
edgeDragged: false,
swiped: false, // used by swipeEvent. differentites between touch and swipe.
trackStyle: {},
trackWidth: 0
// Removed
// transformsEnabled: false,
// $nextArrow: null,
// $prevArrow: null,
// $dots: null,
// $list: null,
// $slideTrack: null,
// $slides: null,
};
module.exports = initialState;
/***/ },
/* 10 */
/***/ function(module, exports) {
'use strict';
var defaultProps = {
className: '',
accessibility: true,
adaptiveHeight: false,
arrows: true,
autoplay: false,
autoplaySpeed: 3000,
centerMode: false,
centerPadding: '50px',
cssEase: 'ease',
dots: false,
dotsClass: 'slick-dots',
draggable: true,
easing: 'linear',
edgeFriction: 0.35,
fade: false,
focusOnSelect: false,
infinite: true,
initialSlide: 0,
lazyLoad: false,
pauseOnHover: true,
responsive: null,
rtl: false,
slide: 'div',
slidesToShow: 1,
slidesToScroll: 1,
speed: 500,
swipe: true,
swipeToSlide: false,
touchMove: true,
touchThreshold: 5,
useCSS: true,
variableWidth: false,
vertical: false,
waitForAnimate: true,
afterChange: null,
beforeChange: null,
edgeEvent: null,
init: null,
swipeEvent: null,
// nextArrow, prevArrow are react componets
nextArrow: null,
prevArrow: null
};
module.exports = defaultProps;
/***/ },
/* 11 */
/***/ 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';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
window.classNames = classNames;
}
}());
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.Track = undefined;
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _objectAssign = __webpack_require__(7);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _classnames = __webpack_require__(11);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var getSlideClasses = function getSlideClasses(spec) {
var slickActive, slickCenter, slickCloned;
var centerOffset, index;
if (spec.rtl) {
index = spec.slideCount - 1 - spec.index;
} else {
index = spec.index;
}
slickCloned = index < 0 || index >= spec.slideCount;
if (spec.centerMode) {
centerOffset = Math.floor(spec.slidesToShow / 2);
slickCenter = (index - spec.currentSlide) % spec.slideCount === 0;
if (index > spec.currentSlide - centerOffset - 1 && index <= spec.currentSlide + centerOffset) {
slickActive = true;
}
} else {
slickActive = spec.currentSlide <= index && index < spec.currentSlide + spec.slidesToShow;
}
return (0, _classnames2.default)({
'slick-slide': true,
'slick-active': slickActive,
'slick-center': slickCenter,
'slick-cloned': slickCloned
});
};
var getSlideStyle = function getSlideStyle(spec) {
var style = {};
if (spec.variableWidth === undefined || spec.variableWidth === false) {
style.width = spec.slideWidth;
}
if (spec.fade) {
style.position = 'relative';
style.left = -spec.index * spec.slideWidth;
style.opacity = spec.currentSlide === spec.index ? 1 : 0;
style.transition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase;
style.WebkitTransition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase;
}
return style;
};
var getKey = function getKey(child, fallbackKey) {
// key could be a zero
return child.key === null || child.key === undefined ? fallbackKey : child.key;
};
var renderSlides = function renderSlides(spec) {
var key;
var slides = [];
var preCloneSlides = [];
var postCloneSlides = [];
var count = _react2.default.Children.count(spec.children);
_react2.default.Children.forEach(spec.children, function (elem, index) {
var child = void 0;
var childOnClickOptions = {
message: 'children',
index: index,
slidesToScroll: spec.slidesToScroll,
currentSlide: spec.currentSlide
};
if (!spec.lazyLoad | (spec.lazyLoad && spec.lazyLoadedList.indexOf(index) >= 0)) {
child = elem;
} else {
child = _react2.default.createElement('div', null);
}
var childStyle = getSlideStyle((0, _objectAssign2.default)({}, spec, { index: index }));
var slickClasses = getSlideClasses((0, _objectAssign2.default)({ index: index }, spec));
var cssClasses;
if (child.props.className) {
cssClasses = (0, _classnames2.default)(slickClasses, child.props.className);
} else {
cssClasses = slickClasses;
}
var onClick = function onClick(e) {
child.props && child.props.onClick && child.props.onClick(e);
if (spec.focusOnSelect) {
spec.focusOnSelect(childOnClickOptions);
}
};
slides.push(_react2.default.cloneElement(child, {
key: 'original' + getKey(child, index),
'data-index': index,
className: cssClasses,
tabIndex: '-1',
style: (0, _objectAssign2.default)({ outline: 'none' }, child.props.style || {}, childStyle),
onClick: onClick
}));
// variableWidth doesn't wrap properly.
if (spec.infinite && spec.fade === false) {
var infiniteCount = spec.variableWidth ? spec.slidesToShow + 1 : spec.slidesToShow;
if (index >= count - infiniteCount) {
key = -(count - index);
preCloneSlides.push(_react2.default.cloneElement(child, {
key: 'precloned' + getKey(child, key),
'data-index': key,
className: cssClasses,
style: (0, _objectAssign2.default)({}, child.props.style || {}, childStyle),
onClick: onClick
}));
}
if (index < infiniteCount) {
key = count + index;
postCloneSlides.push(_react2.default.cloneElement(child, {
key: 'postcloned' + getKey(child, key),
'data-index': key,
className: cssClasses,
style: (0, _objectAssign2.default)({}, child.props.style || {}, childStyle),
onClick: onClick
}));
}
}
});
if (spec.rtl) {
return preCloneSlides.concat(slides, postCloneSlides).reverse();
} else {
return preCloneSlides.concat(slides, postCloneSlides);
}
};
var Track = exports.Track = _react2.default.createClass({
displayName: 'Track',
render: function render() {
var slides = renderSlides.call(this, this.props);
return _react2.default.createElement(
'div',
{ className: 'slick-track', style: this.props.trackStyle },
slides
);
}
});
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.Dots = undefined;
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(11);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var getDotCount = function getDotCount(spec) {
var dots;
dots = Math.ceil(spec.slideCount / spec.slidesToScroll);
return dots;
};
var Dots = exports.Dots = _react2.default.createClass({
displayName: 'Dots',
clickHandler: function clickHandler(options, e) {
// In Autoplay the focus stays on clicked button even after transition
// to next slide. That only goes away by click somewhere outside
e.preventDefault();
this.props.clickHandler(options);
},
render: function render() {
var _this = this;
var dotCount = getDotCount({
slideCount: this.props.slideCount,
slidesToScroll: this.props.slidesToScroll
});
// Apply join & split to Array to pre-fill it for IE8
//
// Credit: http://stackoverflow.com/a/13735425/1849458
var dots = Array.apply(null, Array(dotCount + 1).join('0').split('')).map(function (x, i) {
var leftBound = i * _this.props.slidesToScroll;
var rightBound = i * _this.props.slidesToScroll + (_this.props.slidesToScroll - 1);
var className = (0, _classnames2.default)({
'slick-active': _this.props.currentSlide >= leftBound && _this.props.currentSlide <= rightBound
});
var dotOptions = {
message: 'dots',
index: i,
slidesToScroll: _this.props.slidesToScroll,
currentSlide: _this.props.currentSlide
};
return _react2.default.createElement(
'li',
{ key: i, className: className },
_react2.default.createElement(
'button',
{ onClick: _this.clickHandler.bind(_this, dotOptions) },
i + 1
)
);
});
return _react2.default.createElement(
'ul',
{ className: this.props.dotsClass, style: { display: 'block' } },
dots
);
}
});
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.NextArrow = exports.PrevArrow = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(11);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var PrevArrow = exports.PrevArrow = _react2.default.createClass({
displayName: 'PrevArrow',
clickHandler: function clickHandler(options, e) {
if (e) {
e.preventDefault();
}
this.props.clickHandler(options, e);
},
render: function render() {
var prevClasses = { 'slick-arrow': true, 'slick-prev': true };
var prevHandler = this.clickHandler.bind(this, { message: 'previous' });
if (!this.props.infinite && (this.props.currentSlide === 0 || this.props.slideCount <= this.props.slidesToShow)) {
prevClasses['slick-disabled'] = true;
prevHandler = null;
}
var prevArrowProps = {
key: '0',
'data-role': 'none',
className: (0, _classnames2.default)(prevClasses),
style: { display: 'block' },
onClick: prevHandler
};
var prevArrow;
if (this.props.prevArrow) {
prevArrow = _react2.default.cloneElement(this.props.prevArrow, prevArrowProps);
} else {
prevArrow = _react2.default.createElement(
'button',
_extends({ key: '0', type: 'button' }, prevArrowProps),
' Previous'
);
}
return prevArrow;
}
});
var NextArrow = exports.NextArrow = _react2.default.createClass({
displayName: 'NextArrow',
clickHandler: function clickHandler(options, e) {
if (e) {
e.preventDefault();
}
this.props.clickHandler(options, e);
},
render: function render() {
var nextClasses = { 'slick-arrow': true, 'slick-next': true };
var nextHandler = this.clickHandler.bind(this, { message: 'next' });
if (!this.props.infinite) {
if (this.props.centerMode && this.props.currentSlide >= this.props.slideCount - 1) {
nextClasses['slick-disabled'] = true;
nextHandler = null;
} else {
if (this.props.currentSlide >= this.props.slideCount - this.props.slidesToShow) {
nextClasses['slick-disabled'] = true;
nextHandler = null;
}
}
if (this.props.slideCount <= this.props.slidesToShow) {
nextClasses['slick-disabled'] = true;
nextHandler = null;
}
}
var nextArrowProps = {
key: '1',
'data-role': 'none',
className: (0, _classnames2.default)(nextClasses),
style: { display: 'block' },
onClick: nextHandler
};
var nextArrow;
if (this.props.nextArrow) {
nextArrow = _react2.default.cloneElement(this.props.nextArrow, nextArrowProps);
} else {
nextArrow = _react2.default.createElement(
'button',
_extends({ key: '1', type: 'button' }, nextArrowProps),
' Next'
);
}
return nextArrow;
}
});
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
var camel2hyphen = __webpack_require__(16);
var isDimension = function (feature) {
var re = /[height|width]$/;
return re.test(feature);
};
var obj2mq = function (obj) {
var mq = '';
var features = Object.keys(obj);
features.forEach(function (feature, index) {
var value = obj[feature];
feature = camel2hyphen(feature);
// Add px to dimension features
if (isDimension(feature) && typeof value === 'number') {
value = value + 'px';
}
if (value === true) {
mq += feature;
} else if (value === false) {
mq += 'not ' + feature;
} else {
mq += '(' + feature + ': ' + value + ')';
}
if (index < features.length-1) {
mq += ' and '
}
});
return mq;
};
var json2mq = function (query) {
var mq = '';
if (typeof query === 'string') {
return query;
}
// Handling array of media queries
if (query instanceof Array) {
query.forEach(function (q, index) {
mq += obj2mq(q);
if (index < query.length-1) {
mq += ', '
}
});
return mq;
}
// Handling single media query
return obj2mq(query);
};
module.exports = json2mq;
/***/ },
/* 16 */
/***/ function(module, exports) {
var camel2hyphen = function (str) {
return str
.replace(/[A-Z]/g, function (match) {
return '-' + match.toLowerCase();
})
.toLowerCase();
};
module.exports = camel2hyphen;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var canUseDOM = __webpack_require__(18);
var enquire = canUseDOM && __webpack_require__(19);
var json2mq = __webpack_require__(15);
var ResponsiveMixin = {
media: function (query, handler) {
query = json2mq(query);
if (typeof handler === 'function') {
handler = {
match: handler
};
}
canUseDOM && enquire.register(query, handler);
// Queue the handlers to unregister them at unmount
if (! this._responsiveMediaHandlers) {
this._responsiveMediaHandlers = [];
}
this._responsiveMediaHandlers.push({query: query, handler: handler});
},
componentWillUnmount: function () {
if (this._responsiveMediaHandlers) {
this._responsiveMediaHandlers.forEach(function(obj) {
canUseDOM && enquire.unregister(obj.query, obj.handler);
});
}
}
};
module.exports = ResponsiveMixin;
/***/ },
/* 18 */
/***/ function(module, exports) {
var canUseDOM = !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
module.exports = canUseDOM;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*!
* enquire.js v2.1.1 - Awesome Media Queries in JavaScript
* Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/enquire.js
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
*/
;(function (name, context, factory) {
var matchMedia = window.matchMedia;
if (typeof module !== 'undefined' && module.exports) {
module.exports = factory(matchMedia);
}
else if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
return (context[name] = factory(matchMedia));
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
else {
context[name] = factory(matchMedia);
}
}('enquire', this, function (matchMedia) {
'use strict';
/*jshint unused:false */
/**
* Helper function for iterating over a collection
*
* @param collection
* @param fn
*/
function each(collection, fn) {
var i = 0,
length = collection.length,
cont;
for(i; i < length; i++) {
cont = fn(collection[i], i);
if(cont === false) {
break; //allow early exit
}
}
}
/**
* Helper function for determining whether target object is an array
*
* @param target the object under test
* @return {Boolean} true if array, false otherwise
*/
function isArray(target) {
return Object.prototype.toString.apply(target) === '[object Array]';
}
/**
* Helper function for determining whether target object is a function
*
* @param target the object under test
* @return {Boolean} true if function, false otherwise
*/
function isFunction(target) {
return typeof target === 'function';
}
/**
* Delegate to handle a media query being matched and unmatched.
*
* @param {object} options
* @param {function} options.match callback for when the media query is matched
* @param {function} [options.unmatch] callback for when the media query is unmatched
* @param {function} [options.setup] one-time callback triggered the first time a query is matched
* @param {boolean} [options.deferSetup=false] should the setup callback be run immediately, rather than first time query is matched?
* @constructor
*/
function QueryHandler(options) {
this.options = options;
!options.deferSetup && this.setup();
}
QueryHandler.prototype = {
/**
* coordinates setup of the handler
*
* @function
*/
setup : function() {
if(this.options.setup) {
this.options.setup();
}
this.initialised = true;
},
/**
* coordinates setup and triggering of the handler
*
* @function
*/
on : function() {
!this.initialised && this.setup();
this.options.match && this.options.match();
},
/**
* coordinates the unmatch event for the handler
*
* @function
*/
off : function() {
this.options.unmatch && this.options.unmatch();
},
/**
* called when a handler is to be destroyed.
* delegates to the destroy or unmatch callbacks, depending on availability.
*
* @function
*/
destroy : function() {
this.options.destroy ? this.options.destroy() : this.off();
},
/**
* determines equality by reference.
* if object is supplied compare options, if function, compare match callback
*
* @function
* @param {object || function} [target] the target for comparison
*/
equals : function(target) {
return this.options === target || this.options.match === target;
}
};
/**
* Represents a single media query, manages it's state and registered handlers for this query
*
* @constructor
* @param {string} query the media query string
* @param {boolean} [isUnconditional=false] whether the media query should run regardless of whether the conditions are met. Primarily for helping older browsers deal with mobile-first design
*/
function MediaQuery(query, isUnconditional) {
this.query = query;
this.isUnconditional = isUnconditional;
this.handlers = [];
this.mql = matchMedia(query);
var self = this;
this.listener = function(mql) {
self.mql = mql;
self.assess();
};
this.mql.addListener(this.listener);
}
MediaQuery.prototype = {
/**
* add a handler for this query, triggering if already active
*
* @param {object} handler
* @param {function} handler.match callback for when query is activated
* @param {function} [handler.unmatch] callback for when query is deactivated
* @param {function} [handler.setup] callback for immediate execution when a query handler is registered
* @param {boolean} [handler.deferSetup=false] should the setup callback be deferred until the first time the handler is matched?
*/
addHandler : function(handler) {
var qh = new QueryHandler(handler);
this.handlers.push(qh);
this.matches() && qh.on();
},
/**
* removes the given handler from the collection, and calls it's destroy methods
*
* @param {object || function} handler the handler to remove
*/
removeHandler : function(handler) {
var handlers = this.handlers;
each(handlers, function(h, i) {
if(h.equals(handler)) {
h.destroy();
return !handlers.splice(i,1); //remove from array and exit each early
}
});
},
/**
* Determine whether the media query should be considered a match
*
* @return {Boolean} true if media query can be considered a match, false otherwise
*/
matches : function() {
return this.mql.matches || this.isUnconditional;
},
/**
* Clears all handlers and unbinds events
*/
clear : function() {
each(this.handlers, function(handler) {
handler.destroy();
});
this.mql.removeListener(this.listener);
this.handlers.length = 0; //clear array
},
/*
* Assesses the query, turning on all handlers if it matches, turning them off if it doesn't match
*/
assess : function() {
var action = this.matches() ? 'on' : 'off';
each(this.handlers, function(handler) {
handler[action]();
});
}
};
/**
* Allows for registration of query handlers.
* Manages the query handler's state and is responsible for wiring up browser events
*
* @constructor
*/
function MediaQueryDispatch () {
if(!matchMedia) {
throw new Error('matchMedia not present, legacy browsers require a polyfill');
}
this.queries = {};
this.browserIsIncapable = !matchMedia('only all').matches;
}
MediaQueryDispatch.prototype = {
/**
* Registers a handler for the given media query
*
* @param {string} q the media query
* @param {object || Array || Function} options either a single query handler object, a function, or an array of query handlers
* @param {function} options.match fired when query matched
* @param {function} [options.unmatch] fired when a query is no longer matched
* @param {function} [options.setup] fired when handler first triggered
* @param {boolean} [options.deferSetup=false] whether setup should be run immediately or deferred until query is first matched
* @param {boolean} [shouldDegrade=false] whether this particular media query should always run on incapable browsers
*/
register : function(q, options, shouldDegrade) {
var queries = this.queries,
isUnconditional = shouldDegrade && this.browserIsIncapable;
if(!queries[q]) {
queries[q] = new MediaQuery(q, isUnconditional);
}
//normalise to object in an array
if(isFunction(options)) {
options = { match : options };
}
if(!isArray(options)) {
options = [options];
}
each(options, function(handler) {
queries[q].addHandler(handler);
});
return this;
},
/**
* unregisters a query and all it's handlers, or a specific handler for a query
*
* @param {string} q the media query to target
* @param {object || function} [handler] specific handler to unregister
*/
unregister : function(q, handler) {
var query = this.queries[q];
if(query) {
if(handler) {
query.removeHandler(handler);
}
else {
query.clear();
delete this.queries[q];
}
}
return this;
}
};
return new MediaQueryDispatch();
}));
/***/ }
/******/ ])
});
; |
client/node_modules/uu5g03/dist-node/layout/row.js | UnicornCollege/ucl.itkpd.configurator | import React from 'react';
import {BaseMixin, ElementaryMixin, SectionMixin, CcrWriterMixin, ColorSchemaMixin} from '../common/common.js';
import RowMixin from './row-mixin.js';
import Column from './column.js';
import './row.less';
export const Row = React.createClass({
//@@viewOn:mixins
mixins: [
BaseMixin,
ElementaryMixin,
SectionMixin,
CcrWriterMixin,
ColorSchemaMixin,
RowMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Layout.Row',
classNames: {
main: 'uu5-layout-row row',
flex: 'uu5-layout-row-flex',
flexFull: 'uu5-layout-row-flex-full'
},
defaults: {
childrenLayoutType: ['column', 'columnCollection', 'float'],
childParentsLayoutType: ['root'].concat(['container', 'containerCollection']).concat(['row', 'rowCollection']),
parentsLayoutType: ['container', 'rowCollection']
},
errors: {
childIsWrong: 'Child %s is not column or column collection.'
}
},
//@@viewOff:statics
//@@viewOn:propTypes
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
//@@viewOff:interface
//@@viewOn:overridingMethods
expandChild_: function (child, key) {
var result = child;
if (typeof child.type !== 'function' || !child.type.layoutType || this.getDefault().childrenLayoutType.indexOf(child.type.layoutType) === -1) {
if (child.type && this.getDefault().childParentsLayoutType.indexOf(child.type.layoutType) > -1) {
this.showError('childIsWrong', [child.type.tagName, this.getDefault().childrenLayoutType.join(', ')], {
mixinName: 'UU5_Layout_LayoutMixin',
context: {
child: {
tagName: child.type.tagName,
component: child
}
}
});
} else {
result = (
<Column
parent={this}
id={this.getId() + '-column'}
key={key}
colWidth={child.props.colWidth}
>
{child}
</Column>
);
}
}
return result;
},
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
_getMainAttrs: function () {
var mainAttrs = this.buildMainAttrs();
switch (this.props.display) {
case 'flex':
mainAttrs.className += ' ' + this.getClassName().flex;
break;
case 'flex-full':
mainAttrs.className += ' ' + this.getClassName().flexFull;
break;
}
return mainAttrs;
},//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render: function () {
return (
<div {...this._getMainAttrs()}>
{this.getHeaderChild()}
{this.getFilteredSorterChildren()}
{this.getFooterChild()}
{this.getDisabledCover()}
</div>
);
}
//@@viewOff:render
});
export default Row; |
node_modules/react-dom/lib/ReactDOMTextComponent.js | webtutorial/builder | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
var _prodInvariant = require('./reactProdInvariant'),
_assign = require('object-assign');
var DOMChildrenOperations = require('./DOMChildrenOperations');
var DOMLazyTree = require('./DOMLazyTree');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var escapeTextContentForBrowser = require('./escapeTextContentForBrowser');
var invariant = require('fbjs/lib/invariant');
var validateDOMNesting = require('./validateDOMNesting');
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings between comment nodes so that they
* can undergo the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactDOMTextComponent
* @extends ReactComponent
* @internal
*/
var ReactDOMTextComponent = function (text) {
// TODO: This is really a ReactText (ReactNode), not a ReactElement
this._currentElement = text;
this._stringText = '' + text;
// ReactDOMComponentTree uses these:
this._hostNode = null;
this._hostParent = null;
// Properties
this._domID = 0;
this._mountIndex = 0;
this._closingComment = null;
this._commentNodes = null;
};
_assign(ReactDOMTextComponent.prototype, {
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
if (process.env.NODE_ENV !== 'production') {
var parentInfo;
if (hostParent != null) {
parentInfo = hostParent._ancestorInfo;
} else if (hostContainerInfo != null) {
parentInfo = hostContainerInfo._ancestorInfo;
}
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting(null, this._stringText, this, parentInfo);
}
}
var domID = hostContainerInfo._idCounter++;
var openingValue = ' react-text: ' + domID + ' ';
var closingValue = ' /react-text ';
this._domID = domID;
this._hostParent = hostParent;
if (transaction.useCreateElement) {
var ownerDocument = hostContainerInfo._ownerDocument;
var openingComment = ownerDocument.createComment(openingValue);
var closingComment = ownerDocument.createComment(closingValue);
var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment());
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment));
if (this._stringText) {
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText)));
}
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment));
ReactDOMComponentTree.precacheNode(this, openingComment);
this._closingComment = closingComment;
return lazyTree;
} else {
var escapedText = escapeTextContentForBrowser(this._stringText);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this between comment nodes for the reasons stated
// above, but since this is a situation where React won't take over
// (static pages), we can simply return the text as it is.
return escapedText;
}
return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->';
}
},
/**
* Updates this component by updating the text content.
*
* @param {ReactText} nextText The next text content
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function (nextText, transaction) {
if (nextText !== this._currentElement) {
this._currentElement = nextText;
var nextStringText = '' + nextText;
if (nextStringText !== this._stringText) {
// TODO: Save this as pending props and use performUpdateIfNecessary
// and/or updateComponent to do the actual update for consistency with
// other component types?
this._stringText = nextStringText;
var commentNodes = this.getHostNode();
DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText);
}
}
},
getHostNode: function () {
var hostNode = this._commentNodes;
if (hostNode) {
return hostNode;
}
if (!this._closingComment) {
var openingComment = ReactDOMComponentTree.getNodeFromInstance(this);
var node = openingComment.nextSibling;
while (true) {
!(node != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : _prodInvariant('67', this._domID) : void 0;
if (node.nodeType === 8 && node.nodeValue === ' /react-text ') {
this._closingComment = node;
break;
}
node = node.nextSibling;
}
}
hostNode = [this._hostNode, this._closingComment];
this._commentNodes = hostNode;
return hostNode;
},
unmountComponent: function () {
this._closingComment = null;
this._commentNodes = null;
ReactDOMComponentTree.uncacheNode(this);
}
});
module.exports = ReactDOMTextComponent; |
src/svg-icons/device/signal-cellular-connected-no-internet-4-bar.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularConnectedNoInternet4Bar = (props) => (
<SvgIcon {...props}>
<path d="M20 18h2v-8h-2v8zm0 4h2v-2h-2v2zM2 22h16V8h4V2L2 22z"/>
</SvgIcon>
);
DeviceSignalCellularConnectedNoInternet4Bar = pure(DeviceSignalCellularConnectedNoInternet4Bar);
DeviceSignalCellularConnectedNoInternet4Bar.displayName = 'DeviceSignalCellularConnectedNoInternet4Bar';
DeviceSignalCellularConnectedNoInternet4Bar.muiName = 'SvgIcon';
export default DeviceSignalCellularConnectedNoInternet4Bar;
|
src/client.js | tonimoeckel/lap-counter-react | /**
* 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 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import deepForceUpdate from 'react-deep-force-update';
import queryString from 'query-string';
import { createPath } from 'history/PathUtils';
import App from './components/App';
import createFetch from './createFetch';
import configureStore from './store/configureStore';
import { updateMeta } from './DOMUtils';
import history from './history';
import createApolloClient from './core/createApolloClient';
import router from './router';
const apolloClient = createApolloClient();
/* eslint-disable global-require */
// Universal HTTP client
const fetch = createFetch(self.fetch, {
baseUrl: window.App.apiUrl,
});
// Global (context) variables that can be easily accessed from any React component
// https://facebook.github.io/react/docs/context.html
const context = {
// Enables critical path CSS rendering
// https://github.com/kriasoft/isomorphic-style-loader
insertCss: (...styles) => {
// eslint-disable-next-line no-underscore-dangle
const removeCss = styles.map(x => x._insertCss());
return () => {
removeCss.forEach(f => f());
};
},
// For react-apollo
client: apolloClient,
// Initialize a new Redux store
// http://redux.js.org/docs/basics/UsageWithReact.html
store: configureStore(window.App.state, { apolloClient, fetch, history }),
fetch,
storeSubscription: null,
};
// Switch off the native scroll restoration behavior and handle it manually
// https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration
const scrollPositionsHistory = {};
if (window.history && 'scrollRestoration' in window.history) {
window.history.scrollRestoration = 'manual';
}
let onRenderComplete = function initialRenderComplete() {
const elem = document.getElementById('css');
if (elem) elem.parentNode.removeChild(elem);
onRenderComplete = function renderComplete(route, location) {
document.title = route.title;
updateMeta('description', route.description);
// Update necessary tags in <head> at runtime here, ie:
// updateMeta('keywords', route.keywords);
// updateCustomMeta('og:url', route.canonicalUrl);
// updateCustomMeta('og:image', route.imageUrl);
// updateLink('canonical', route.canonicalUrl);
// etc.
let scrollX = 0;
let scrollY = 0;
const pos = scrollPositionsHistory[location.key];
if (pos) {
scrollX = pos.scrollX;
scrollY = pos.scrollY;
} else {
const targetHash = location.hash.substr(1);
if (targetHash) {
const target = document.getElementById(targetHash);
if (target) {
scrollY = window.pageYOffset + target.getBoundingClientRect().top;
}
}
}
// Restore the scroll position if it was saved into the state
// or scroll to the given #hash anchor
// or scroll to top of the page
window.scrollTo(scrollX, scrollY);
// Google Analytics tracking. Don't send 'pageview' event after
// the initial rendering, as it was already sent
if (window.ga) {
window.ga('send', 'pageview', createPath(location));
}
};
};
const container = document.getElementById('app');
let appInstance;
let currentLocation = history.location;
// Re-render the app when window.location changes
async function onLocationChange(location, action) {
// Remember the latest scroll position for the previous location
scrollPositionsHistory[currentLocation.key] = {
scrollX: window.pageXOffset,
scrollY: window.pageYOffset,
};
// Delete stored scroll position for next page if any
if (action === 'PUSH') {
delete scrollPositionsHistory[location.key];
}
currentLocation = location;
try {
// Traverses the list of routes in the order they are defined until
// it finds the first route that matches provided URL path string
// and whose action method returns anything other than `undefined`.
const route = await router.resolve({
...context,
path: location.pathname,
query: queryString.parse(location.search),
});
// Prevent multiple page renders during the routing process
if (currentLocation.key !== location.key) {
return;
}
if (route.redirect) {
history.replace(route.redirect);
return;
}
appInstance = ReactDOM.render(
<App context={context}>
{route.component}
</App>,
container,
() => onRenderComplete(route, location),
);
} catch (error) {
if (__DEV__) {
throw error;
}
console.error(error);
// Do a full page reload if error occurs during client-side navigation
if (action && currentLocation.key === location.key) {
window.location.reload();
}
}
}
// Handle client-side navigation by using HTML5 History API
// For more information visit https://github.com/mjackson/history#readme
history.listen(onLocationChange);
onLocationChange(currentLocation);
// Enable Hot Module Replacement (HMR)
if (module.hot) {
module.hot.accept('./router', () => {
if (appInstance) {
// Force-update the whole tree, including components that refuse to update
deepForceUpdate(appInstance);
}
onLocationChange(currentLocation);
});
}
|
src/svg-icons/image/brush.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBrush = (props) => (
<SvgIcon {...props}>
<path d="M7 14c-1.66 0-3 1.34-3 3 0 1.31-1.16 2-2 2 .92 1.22 2.49 2 4 2 2.21 0 4-1.79 4-4 0-1.66-1.34-3-3-3zm13.71-9.37l-1.34-1.34c-.39-.39-1.02-.39-1.41 0L9 12.25 11.75 15l8.96-8.96c.39-.39.39-1.02 0-1.41z"/>
</SvgIcon>
);
ImageBrush = pure(ImageBrush);
ImageBrush.displayName = 'ImageBrush';
export default ImageBrush;
|
benchmarks/dom-comparison/src/implementations/react-native-web/Tweet/TweetTextPart.js | risetechnologies/fela | /* eslint-disable react/prop-types */
import { Image, StyleSheet, Text } from 'react-native';
import PropTypes from 'prop-types';
import React from 'react';
import theme from './theme';
const createTextEntity = ({ part }) => <Text>{`${part.prefix}${part.text}`}</Text>;
const createTwemojiEntity = ({ part }) => (
<Image
accessibilityLabel={part.text}
draggable={false}
source={{ uri: part.emoji }}
style={styles.twemoji}
/>
);
// @mention, #hashtag, $cashtag
const createSymbolEntity = ({ displayMode, part }) => {
const links = displayMode === 'links';
return (
<Text accessibilityRole={links ? 'link' : null} href={part.url} style={[links && styles.link]}>
{`${part.prefix}${part.text}`}
</Text>
);
};
// internal links
const createLinkEntity = ({ displayMode, part }) => {
const { displayUrl, linkRelation, url } = part;
const links = displayMode === 'links';
return (
<Text
accessibilityRole={links ? 'link' : null}
href={url}
rel={links ? linkRelation : null}
style={[links && styles.link]}
>
{displayUrl}
</Text>
);
};
// external links
const createExternalLinkEntity = ({ displayMode, part }) => {
const { displayUrl, linkRelation, url } = part;
const links = displayMode === 'links';
return (
<Text
accessibilityRole={links ? 'link' : null}
href={url}
rel={links ? linkRelation : null}
style={[links && styles.link]}
target="_blank"
>
{displayUrl}
</Text>
);
};
class TweetTextPart extends React.Component {
static displayName = 'TweetTextPart';
static propTypes = {
displayMode: PropTypes.oneOf(['links', 'no-links']),
part: PropTypes.object
};
static defaultProps = {
displayMode: 'links'
};
render() {
let renderer;
const { isEmoji, isEntity, isHashtag, isMention, isMedia, isUrl } = this.props.part;
if (isEmoji || isEntity || isUrl || isMedia) {
if (isUrl) {
renderer = createExternalLinkEntity;
} else if (isHashtag || isMention) {
renderer = createSymbolEntity;
} else if (isEmoji) {
renderer = createTwemojiEntity;
} else {
renderer = createLinkEntity;
}
} else {
renderer = createTextEntity;
}
return renderer(this.props);
}
}
const styles = StyleSheet.create({
link: {
color: theme.colors.blue,
textDecorationLine: 'none',
unicodeBidi: 'embed'
},
twemoji: {
display: 'inline-block',
height: '1.25em',
width: '1.25em',
paddingRight: '0.05em',
paddingLeft: '0.1em',
textAlignVertical: '-0.2em'
}
});
export default TweetTextPart;
|
src/components/utilities/RewardCalculator.js | whphhg/vcash-ui | import React from 'react'
import { translate } from 'react-i18next'
import { action, computed, extendObservable } from 'mobx'
import { inject, observer } from 'mobx-react'
import { incentivePercent, powReward } from '../../utilities/blockRewards.js'
/** Ant Design */
import Input from 'antd/lib/input'
@translate(['common'])
@inject('gui', 'wallet')
@observer
class RewardCalculator extends React.Component {
constructor(props) {
super(props)
this.t = props.t
this.gui = props.gui
this.wallet = props.wallet
/** Extend the component with observable properties. */
extendObservable(this, { enteredBlock: '' })
}
/**
* Get block.
* @function block
* @return {number} Entered or current block.
*/
@computed
get block() {
return this.enteredBlock.length === 0
? this.wallet.info.blocks
: Math.round(this.enteredBlock)
}
/**
* Get Proof-of-Work reward.
* @function powReward
* @return {number} Reward.
*/
@computed
get powReward() {
return powReward(this.block)
}
/**
* Get incentive percent of PoW reward.
* @function incentivePercent
* @return {number} Percent.
*/
@computed
get incentivePercent() {
return incentivePercent(this.block)
}
/**
* Get mining share.
* @function miningReward
* @return {number} Reward.
*/
@computed
get miningReward() {
return this.powReward - this.incentiveReward
}
/**
* Get incentive share.
* @function incentiveReward
* @return {number} Reward.
*/
@computed
get incentiveReward() {
return this.powReward / 100 * this.incentivePercent
}
/**
* Set block.
* @function setBlock
* @param {string} block - Entered block.
*/
@action
setBlock = block => {
if (block.toString().match(/^[0-9]{0,7}$/) !== null) {
this.enteredBlock = block
}
}
render() {
return (
<div className="flex">
<div style={{ margin: '0 36px 0 0' }}>
<div className="flex" style={{ margin: '0 0 10px 0' }}>
<i className="material-icons md-16">extension</i>
<p>{this.t('block')}</p>
</div>
<div className="flex">
<i className="material-icons md-16">star</i>
<p>{this.t('powReward')}</p>
</div>
<div className="flex">
<i className="material-icons md-16">developer_board</i>
<p>{this.t('miningReward')}</p>
</div>
<div className="flex">
<i className="material-icons md-16">event_seat</i>
<p>{this.t('incentiveReward')}</p>
</div>
</div>
<div style={{ margin: '0 0 2px 0' }}>
<Input
onChange={e => this.setBlock(e.target.value)}
placeholder={this.block}
size="small"
style={{ margin: '0 0 10px 0', width: '60px' }}
value={this.enteredBlock}
/>
<p>
<span style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(this.gui.language, {
minimumFractionDigits: 6,
maximumFractionDigits: 6
}).format(this.powReward)}
</span>{' '}
XVC
</p>
<p>
<span style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(this.gui.language, {
minimumFractionDigits: 6,
maximumFractionDigits: 6
}).format(this.miningReward)}
</span>{' '}
XVC ({100 - this.incentivePercent}%)
</p>
<p>
<span style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(this.gui.language, {
minimumFractionDigits: 6,
maximumFractionDigits: 6
}).format(this.incentiveReward)}
</span>{' '}
XVC ({this.incentivePercent}%)
</p>
</div>
</div>
)
}
}
export default RewardCalculator
|
ajax/libs/yui/3.5.0/simpleyui/simpleyui-debug.js | coupang/cdnjs | /**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and
* the core utilities for the library.
* @module yui
* @submodule yui-base
*/
if (typeof YUI != 'undefined') {
YUI._YUI = YUI;
}
/**
The YUI global namespace object. If YUI is already defined, the
existing YUI object will not be overwritten so that defined
namespaces are preserved. It is the constructor for the object
the end user interacts with. As indicated below, each instance
has full custom event support, but only if the event system
is available. This is a self-instantiable factory function. You
can invoke it directly like this:
YUI().use('*', function(Y) {
// ready
});
But it also works like this:
var Y = YUI();
Configuring the YUI object:
YUI({
debug: true,
combine: false
}).use('node', function(Y) {
//Node is ready to use
});
See the API docs for the <a href="config.html">Config</a> class
for the complete list of supported configuration properties accepted
by the YUI constuctor.
@class YUI
@constructor
@global
@uses EventTarget
@param [o]* {Object} 0..n optional configuration objects. these values
are store in Y.config. See <a href="config.html">Config</a> for the list of supported
properties.
*/
/*global YUI*/
/*global YUI_config*/
var YUI = function() {
var i = 0,
Y = this,
args = arguments,
l = args.length,
instanceOf = function(o, type) {
return (o && o.hasOwnProperty && (o instanceof type));
},
gconf = (typeof YUI_config !== 'undefined') && YUI_config;
if (!(instanceOf(Y, YUI))) {
Y = new YUI();
} else {
// set up the core environment
Y._init();
/**
YUI.GlobalConfig is a master configuration that might span
multiple contexts in a non-browser environment. It is applied
first to all instances in all contexts.
@property GlobalConfig
@type {Object}
@global
@static
@example
YUI.GlobalConfig = {
filter: 'debug'
};
YUI().use('node', function(Y) {
//debug files used here
});
YUI({
filter: 'min'
}).use('node', function(Y) {
//min files used here
});
*/
if (YUI.GlobalConfig) {
Y.applyConfig(YUI.GlobalConfig);
}
/**
YUI_config is a page-level config. It is applied to all
instances created on the page. This is applied after
YUI.GlobalConfig, and before the instance level configuration
objects.
@global
@property YUI_config
@type {Object}
@example
//Single global var to include before YUI seed file
YUI_config = {
filter: 'debug'
};
YUI().use('node', function(Y) {
//debug files used here
});
YUI({
filter: 'min'
}).use('node', function(Y) {
//min files used here
});
*/
if (gconf) {
Y.applyConfig(gconf);
}
// bind the specified additional modules for this instance
if (!l) {
Y._setup();
}
}
if (l) {
// Each instance can accept one or more configuration objects.
// These are applied after YUI.GlobalConfig and YUI_Config,
// overriding values set in those config files if there is a '
// matching property.
for (; i < l; i++) {
Y.applyConfig(args[i]);
}
Y._setup();
}
Y.instanceOf = instanceOf;
return Y;
};
(function() {
var proto, prop,
VERSION = '@VERSION@',
PERIOD = '.',
BASE = 'http://yui.yahooapis.com/',
DOC_LABEL = 'yui3-js-enabled',
CSS_STAMP_EL = 'yui3-css-stamp',
NOOP = function() {},
SLICE = Array.prototype.slice,
APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo
'io.xdrResponse': 1, // can call. this should
'SWF.eventHandler': 1 }, // be done at build time
hasWin = (typeof window != 'undefined'),
win = (hasWin) ? window : null,
doc = (hasWin) ? win.document : null,
docEl = doc && doc.documentElement,
docClass = docEl && docEl.className,
instances = {},
time = new Date().getTime(),
add = function(el, type, fn, capture) {
if (el && el.addEventListener) {
el.addEventListener(type, fn, capture);
} else if (el && el.attachEvent) {
el.attachEvent('on' + type, fn);
}
},
remove = function(el, type, fn, capture) {
if (el && el.removeEventListener) {
// this can throw an uncaught exception in FF
try {
el.removeEventListener(type, fn, capture);
} catch (ex) {}
} else if (el && el.detachEvent) {
el.detachEvent('on' + type, fn);
}
},
handleLoad = function() {
YUI.Env.windowLoaded = true;
YUI.Env.DOMReady = true;
if (hasWin) {
remove(window, 'load', handleLoad);
}
},
getLoader = function(Y, o) {
var loader = Y.Env._loader;
if (loader) {
//loader._config(Y.config);
loader.ignoreRegistered = false;
loader.onEnd = null;
loader.data = null;
loader.required = [];
loader.loadType = null;
} else {
loader = new Y.Loader(Y.config);
Y.Env._loader = loader;
}
YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, [ 'loader-base', 'loader-rollup', 'loader-yui3' ]));
return loader;
},
clobber = function(r, s) {
for (var i in s) {
if (s.hasOwnProperty(i)) {
r[i] = s[i];
}
}
},
ALREADY_DONE = { success: true };
// Stamp the documentElement (HTML) with a class of "yui-loaded" to
// enable styles that need to key off of JS being enabled.
if (docEl && docClass.indexOf(DOC_LABEL) == -1) {
if (docClass) {
docClass += ' ';
}
docClass += DOC_LABEL;
docEl.className = docClass;
}
if (VERSION.indexOf('@') > -1) {
VERSION = '3.3.0'; // dev time hack for cdn test
}
proto = {
/**
* Applies a new configuration object to the YUI instance config.
* This will merge new group/module definitions, and will also
* update the loader cache if necessary. Updating Y.config directly
* will not update the cache.
* @method applyConfig
* @param {Object} o the configuration object.
* @since 3.2.0
*/
applyConfig: function(o) {
o = o || NOOP;
var attr,
name,
// detail,
config = this.config,
mods = config.modules,
groups = config.groups,
aliases = config.aliases,
loader = this.Env._loader;
for (name in o) {
if (o.hasOwnProperty(name)) {
attr = o[name];
if (mods && name == 'modules') {
clobber(mods, attr);
} else if (aliases && name == 'aliases') {
clobber(aliases, attr);
} else if (groups && name == 'groups') {
clobber(groups, attr);
} else if (name == 'win') {
config[name] = (attr && attr.contentWindow) || attr;
config.doc = config[name] ? config[name].document : null;
} else if (name == '_yuid') {
// preserve the guid
} else {
config[name] = attr;
}
}
}
if (loader) {
loader._config(o);
}
},
/**
* Old way to apply a config to the instance (calls `applyConfig` under the hood)
* @private
* @method _config
* @param {Object} o The config to apply
*/
_config: function(o) {
this.applyConfig(o);
},
/**
* Initialize this YUI instance
* @private
* @method _init
*/
_init: function() {
var filter, el,
Y = this,
G_ENV = YUI.Env,
Env = Y.Env,
prop;
/**
* The version number of the YUI instance.
* @property version
* @type string
*/
Y.version = VERSION;
if (!Env) {
Y.Env = {
core: ['get','features','intl-base','yui-log','yui-later'],
mods: {}, // flat module map
versions: {}, // version module map
base: BASE,
cdn: BASE + VERSION + '/build/',
// bootstrapped: false,
_idx: 0,
_used: {},
_attached: {},
_missed: [],
_yidx: 0,
_uidx: 0,
_guidp: 'y',
_loaded: {},
// serviced: {},
// Regex in English:
// I'll start at the \b(simpleyui).
// 1. Look in the test string for "simpleyui" or "yui" or
// "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it
// can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string.
// 2. After #1 must come a forward slash followed by the string matched in #1, so
// "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants".
// 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min",
// so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt".
// 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js"
// 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string,
// then capture the junk between the LAST "&" and the string in 1-4. So
// "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js"
// will capture "3.3.0/build/"
//
// Regex Exploded:
// (?:\? Find a ?
// (?:[^&]*&) followed by 0..n characters followed by an &
// * in fact, find as many sets of characters followed by a & as you can
// ([^&]*) capture the stuff after the last & in \1
// )? but it's ok if all this ?junk&more_junk stuff isn't even there
// \b(simpleyui| after a word break find either the string "simpleyui" or
// yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters
// ) and store the simpleyui or yui-* string in \2
// \/\2 then comes a / followed by the simpleyui or yui-* string in \2
// (?:-(min|debug))? optionally followed by "-min" or "-debug"
// .js and ending in ".js"
_BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/,
parseBasePath: function(src, pattern) {
var match = src.match(pattern),
path, filter;
if (match) {
path = RegExp.leftContext || src.slice(0, src.indexOf(match[0]));
// this is to set up the path to the loader. The file
// filter for loader should match the yui include.
filter = match[3];
// extract correct path for mixed combo urls
// http://yuilibrary.com/projects/yui3/ticket/2528423
if (match[1]) {
path += '?' + match[1];
}
path = {
filter: filter,
path: path
}
}
return path;
},
getBase: G_ENV && G_ENV.getBase ||
function(pattern) {
var nodes = (doc && doc.getElementsByTagName('script')) || [],
path = Env.cdn, parsed,
i, len, src;
for (i = 0, len = nodes.length; i < len; ++i) {
src = nodes[i].src;
if (src) {
parsed = Y.Env.parseBasePath(src, pattern);
if (parsed) {
filter = parsed.filter;
path = parsed.path;
break;
}
}
}
// use CDN default
return path;
}
};
Env = Y.Env;
Env._loaded[VERSION] = {};
if (G_ENV && Y !== YUI) {
Env._yidx = ++G_ENV._yidx;
Env._guidp = ('yui_' + VERSION + '_' +
Env._yidx + '_' + time).replace(/\./g, '_');
} else if (YUI._YUI) {
G_ENV = YUI._YUI.Env;
Env._yidx += G_ENV._yidx;
Env._uidx += G_ENV._uidx;
for (prop in G_ENV) {
if (!(prop in Env)) {
Env[prop] = G_ENV[prop];
}
}
delete YUI._YUI;
}
Y.id = Y.stamp(Y);
instances[Y.id] = Y;
}
Y.constructor = YUI;
// configuration defaults
Y.config = Y.config || {
bootstrap: true,
cacheUse: true,
debug: true,
doc: doc,
fetchCSS: true,
throwFail: true,
useBrowserConsole: true,
useNativeES5: true,
win: win
};
//Register the CSS stamp element
if (doc && !doc.getElementById(CSS_STAMP_EL)) {
el = doc.createElement('div');
el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>';
YUI.Env.cssStampEl = el.firstChild;
docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild);
}
Y.config.lang = Y.config.lang || 'en-US';
Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE);
if (!filter || (!('mindebug').indexOf(filter))) {
filter = 'min';
}
filter = (filter) ? '-' + filter : filter;
Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js';
},
/**
* Finishes the instance setup. Attaches whatever modules were defined
* when the yui modules was registered.
* @method _setup
* @private
*/
_setup: function(o) {
var i, Y = this,
core = [],
mods = YUI.Env.mods,
//extras = Y.config.core || ['get','features','intl-base','yui-log','yui-later'];
extras = Y.config.core || [].concat(YUI.Env.core); //Clone it..
for (i = 0; i < extras.length; i++) {
if (mods[extras[i]]) {
core.push(extras[i]);
}
}
Y._attach(['yui-base']);
Y._attach(core);
if (Y.Loader) {
getLoader(Y);
}
// Y.log(Y.id + ' initialized', 'info', 'yui');
},
/**
* Executes a method on a YUI instance with
* the specified id if the specified method is whitelisted.
* @method applyTo
* @param id {String} the YUI instance id.
* @param method {String} the name of the method to exectute.
* Ex: 'Object.keys'.
* @param args {Array} the arguments to apply to the method.
* @return {Object} the return value from the applied method or null.
*/
applyTo: function(id, method, args) {
if (!(method in APPLY_TO_AUTH)) {
this.log(method + ': applyTo not allowed', 'warn', 'yui');
return null;
}
var instance = instances[id], nest, m, i;
if (instance) {
nest = method.split('.');
m = instance;
for (i = 0; i < nest.length; i = i + 1) {
m = m[nest[i]];
if (!m) {
this.log('applyTo not found: ' + method, 'warn', 'yui');
}
}
return m && m.apply(instance, args);
}
return null;
},
/**
Registers a module with the YUI global. The easiest way to create a
first-class YUI module is to use the YUI component build tool.
http://yuilibrary.com/projects/builder
The build system will produce the `YUI.add` wrapper for you module, along
with any configuration info required for the module.
@method add
@param name {String} module name.
@param fn {Function} entry point into the module that is used to bind module to the YUI instance.
@param {YUI} fn.Y The YUI instance this module is executed in.
@param {String} fn.name The name of the module
@param version {String} version string.
@param details {Object} optional config data:
@param details.requires {Array} features that must be present before this module can be attached.
@param details.optional {Array} optional features that should be present if loadOptional
is defined. Note: modules are not often loaded this way in YUI 3,
but this field is still useful to inform the user that certain
features in the component will require additional dependencies.
@param details.use {Array} features that are included within this module which need to
be attached automatically when this module is attached. This
supports the YUI 3 rollup system -- a module with submodules
defined will need to have the submodules listed in the 'use'
config. The YUI component build tool does this for you.
@return {YUI} the YUI instance.
@example
YUI.add('davglass', function(Y, name) {
Y.davglass = function() {
alert('Dav was here!');
};
}, '3.4.0', { requires: ['yui-base', 'harley-davidson', 'mt-dew'] });
*/
add: function(name, fn, version, details) {
details = details || {};
var env = YUI.Env,
mod = {
name: name,
fn: fn,
version: version,
details: details
},
loader,
i, versions = env.versions;
env.mods[name] = mod;
versions[version] = versions[version] || {};
versions[version][name] = mod;
for (i in instances) {
if (instances.hasOwnProperty(i)) {
loader = instances[i].Env._loader;
if (loader) {
if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) {
loader.addModule(details, name);
}
}
}
}
return this;
},
/**
* Executes the function associated with each required
* module, binding the module to the YUI instance.
* @param {Array} r The array of modules to attach
* @param {Boolean} [moot=false] Don't throw a warning if the module is not attached
* @method _attach
* @private
*/
_attach: function(r, moot) {
var i, name, mod, details, req, use, after,
mods = YUI.Env.mods,
aliases = YUI.Env.aliases,
Y = this, j,
loader = Y.Env._loader,
done = Y.Env._attached,
len = r.length, loader,
c = [];
//Check for conditional modules (in a second+ instance) and add their requirements
//TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass
for (i = 0; i < len; i++) {
name = r[i];
mod = mods[name];
c.push(name);
if (loader && loader.conditions[name]) {
Y.Object.each(loader.conditions[name], function(def) {
var go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y)));
if (go) {
c.push(def.name);
}
});
}
}
r = c;
len = r.length;
for (i = 0; i < len; i++) {
if (!done[r[i]]) {
name = r[i];
mod = mods[name];
if (aliases && aliases[name]) {
Y._attach(aliases[name]);
continue;
}
if (!mod) {
if (loader && loader.moduleInfo[name]) {
mod = loader.moduleInfo[name];
moot = true;
}
// Y.log('no js def for: ' + name, 'info', 'yui');
//if (!loader || !loader.moduleInfo[name]) {
//if ((!loader || !loader.moduleInfo[name]) && !moot) {
if (!moot && name) {
if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) {
Y.Env._missed.push(name);
Y.Env._missed = Y.Array.dedupe(Y.Env._missed);
Y.message('NOT loaded: ' + name, 'warn', 'yui');
}
}
} else {
done[name] = true;
//Don't like this, but in case a mod was asked for once, then we fetch it
//We need to remove it from the missed list ^davglass
for (j = 0; j < Y.Env._missed.length; j++) {
if (Y.Env._missed[j] === name) {
Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui');
Y.Env._missed.splice(j, 1);
}
}
details = mod.details;
req = details.requires;
use = details.use;
after = details.after;
if (req) {
for (j = 0; j < req.length; j++) {
if (!done[req[j]]) {
if (!Y._attach(req)) {
return false;
}
break;
}
}
}
if (after) {
for (j = 0; j < after.length; j++) {
if (!done[after[j]]) {
if (!Y._attach(after, true)) {
return false;
}
break;
}
}
}
if (mod.fn) {
try {
mod.fn(Y, name);
} catch (e) {
Y.error('Attach error: ' + name, e, name);
return false;
}
}
if (use) {
for (j = 0; j < use.length; j++) {
if (!done[use[j]]) {
if (!Y._attach(use)) {
return false;
}
break;
}
}
}
}
}
}
return true;
},
/**
* Attaches one or more modules to the YUI instance. When this
* is executed, the requirements are analyzed, and one of
* several things can happen:
*
* * All requirements are available on the page -- The modules
* are attached to the instance. If supplied, the use callback
* is executed synchronously.
*
* * Modules are missing, the Get utility is not available OR
* the 'bootstrap' config is false -- A warning is issued about
* the missing modules and all available modules are attached.
*
* * Modules are missing, the Loader is not available but the Get
* utility is and boostrap is not false -- The loader is bootstrapped
* before doing the following....
*
* * Modules are missing and the Loader is available -- The loader
* expands the dependency tree and fetches missing modules. When
* the loader is finshed the callback supplied to use is executed
* asynchronously.
*
* @method use
* @param modules* {String|Array} 1-n modules to bind (uses arguments array).
* @param [callback] {Function} callback function executed when
* the instance has the required functionality. If included, it
* must be the last parameter.
* @param callback.Y {YUI} The `YUI` instance created for this sandbox
* @param callback.data {Object} Object data returned from `Loader`.
*
* @example
* // loads and attaches dd and its dependencies
* YUI().use('dd', function(Y) {});
*
* // loads and attaches dd and node as well as all of their dependencies (since 3.4.0)
* YUI().use(['dd', 'node'], function(Y) {});
*
* // attaches all modules that are available on the page
* YUI().use('*', function(Y) {});
*
* // intrinsic YUI gallery support (since 3.1.0)
* YUI().use('gallery-yql', function(Y) {});
*
* // intrinsic YUI 2in3 support (since 3.1.0)
* YUI().use('yui2-datatable', function(Y) {});
*
* @return {YUI} the YUI instance.
*/
use: function() {
var args = SLICE.call(arguments, 0),
callback = args[args.length - 1],
Y = this,
i = 0,
a = [],
name,
Env = Y.Env,
provisioned = true;
// The last argument supplied to use can be a load complete callback
if (Y.Lang.isFunction(callback)) {
args.pop();
} else {
callback = null;
}
if (Y.Lang.isArray(args[0])) {
args = args[0];
}
if (Y.config.cacheUse) {
while ((name = args[i++])) {
if (!Env._attached[name]) {
provisioned = false;
break;
}
}
if (provisioned) {
if (args.length) {
Y.log('already provisioned: ' + args, 'info', 'yui');
}
Y._notify(callback, ALREADY_DONE, args);
return Y;
}
}
if (Y._loading) {
Y._useQueue = Y._useQueue || new Y.Queue();
Y._useQueue.add([args, callback]);
} else {
Y._use(args, function(Y, response) {
Y._notify(callback, response, args);
});
}
return Y;
},
/**
* Notify handler from Loader for attachment/load errors
* @method _notify
* @param callback {Function} The callback to pass to the `Y.config.loadErrorFn`
* @param response {Object} The response returned from Loader
* @param args {Array} The aruments passed from Loader
* @private
*/
_notify: function(callback, response, args) {
if (!response.success && this.config.loadErrorFn) {
this.config.loadErrorFn.call(this, this, callback, response, args);
} else if (callback) {
try {
callback(this, response);
} catch (e) {
this.error('use callback error', e, args);
}
}
},
/**
* This private method is called from the `use` method queue. To ensure that only one set of loading
* logic is performed at a time.
* @method _use
* @private
* @param args* {String} 1-n modules to bind (uses arguments array).
* @param *callback {Function} callback function executed when
* the instance has the required functionality. If included, it
* must be the last parameter.
*/
_use: function(args, callback) {
if (!this.Array) {
this._attach(['yui-base']);
}
var len, loader, handleBoot, handleRLS,
Y = this,
G_ENV = YUI.Env,
mods = G_ENV.mods,
Env = Y.Env,
used = Env._used,
aliases = G_ENV.aliases,
queue = G_ENV._loaderQueue,
firstArg = args[0],
YArray = Y.Array,
config = Y.config,
boot = config.bootstrap,
missing = [],
r = [],
ret = true,
fetchCSS = config.fetchCSS,
process = function(names, skip) {
var i = 0, a = [];
if (!names.length) {
return;
}
if (aliases) {
for (i = 0; i < names.length; i++) {
if (aliases[names[i]]) {
a = [].concat(a, aliases[names[i]]);
} else {
a.push(names[i]);
}
}
names = a;
}
YArray.each(names, function(name) {
// add this module to full list of things to attach
if (!skip) {
r.push(name);
}
// only attach a module once
if (used[name]) {
return;
}
var m = mods[name], req, use;
if (m) {
used[name] = true;
req = m.details.requires;
use = m.details.use;
} else {
// CSS files don't register themselves, see if it has
// been loaded
if (!G_ENV._loaded[VERSION][name]) {
missing.push(name);
} else {
used[name] = true; // probably css
}
}
// make sure requirements are attached
if (req && req.length) {
process(req);
}
// make sure we grab the submodule dependencies too
if (use && use.length) {
process(use, 1);
}
});
},
handleLoader = function(fromLoader) {
var response = fromLoader || {
success: true,
msg: 'not dynamic'
},
redo, origMissing,
ret = true,
data = response.data;
Y._loading = false;
if (data) {
origMissing = missing;
missing = [];
r = [];
process(data);
redo = missing.length;
if (redo) {
if (missing.sort().join() ==
origMissing.sort().join()) {
redo = false;
}
}
}
if (redo && data) {
Y._loading = true;
Y._use(missing, function() {
Y.log('Nested use callback: ' + data, 'info', 'yui');
if (Y._attach(data)) {
Y._notify(callback, response, data);
}
});
} else {
if (data) {
// Y.log('attaching from loader: ' + data, 'info', 'yui');
ret = Y._attach(data);
}
if (ret) {
Y._notify(callback, response, args);
}
}
if (Y._useQueue && Y._useQueue.size() && !Y._loading) {
Y._use.apply(Y, Y._useQueue.next());
}
};
// Y.log(Y.id + ': use called: ' + a + ' :: ' + callback, 'info', 'yui');
// YUI().use('*'); // bind everything available
if (firstArg === '*') {
ret = Y._attach(Y.Object.keys(mods));
if (ret) {
handleLoader();
}
return Y;
}
if (mods['loader'] && !Y.Loader) {
Y.log('Loader was found in meta, but it is not attached. Attaching..', 'info', 'yui');
Y._attach(['loader']);
}
// Y.log('before loader requirements: ' + args, 'info', 'yui');
// use loader to expand dependencies and sort the
// requirements if it is available.
if (boot && Y.Loader && args.length) {
loader = getLoader(Y);
loader.require(args);
loader.ignoreRegistered = true;
loader._boot = true;
loader.calculate(null, (fetchCSS) ? null : 'js');
args = loader.sorted;
loader._boot = false;
}
// process each requirement and any additional requirements
// the module metadata specifies
process(args);
len = missing.length;
if (len) {
missing = Y.Object.keys(YArray.hash(missing));
len = missing.length;
Y.log('Modules missing: ' + missing + ', ' + missing.length, 'info', 'yui');
}
// dynamic load
if (boot && len && Y.Loader) {
// Y.log('Using loader to fetch missing deps: ' + missing, 'info', 'yui');
Y.log('Using Loader', 'info', 'yui');
Y._loading = true;
loader = getLoader(Y);
loader.onEnd = handleLoader;
loader.context = Y;
loader.data = args;
loader.ignoreRegistered = false;
loader.require(args);
loader.insert(null, (fetchCSS) ? null : 'js');
} else if (boot && len && Y.Get && !Env.bootstrapped) {
Y._loading = true;
handleBoot = function() {
Y._loading = false;
queue.running = false;
Env.bootstrapped = true;
G_ENV._bootstrapping = false;
if (Y._attach(['loader'])) {
Y._use(args, callback);
}
};
if (G_ENV._bootstrapping) {
Y.log('Waiting for loader', 'info', 'yui');
queue.add(handleBoot);
} else {
G_ENV._bootstrapping = true;
Y.log('Fetching loader: ' + config.base + config.loaderPath, 'info', 'yui');
Y.Get.script(config.base + config.loaderPath, {
onEnd: handleBoot
});
}
} else {
Y.log('Attaching available dependencies: ' + args, 'info', 'yui');
ret = Y._attach(args);
if (ret) {
handleLoader();
}
}
return Y;
},
/**
Adds a namespace object onto the YUI global if called statically.
// creates YUI.your.namespace.here as nested objects
YUI.namespace("your.namespace.here");
If called as a method on a YUI <em>instance</em>, it creates the
namespace on the instance.
// creates Y.property.package
Y.namespace("property.package");
Dots in the input string cause `namespace` to create nested objects for
each token. If any part of the requested namespace already exists, the
current object will be left in place. This allows multiple calls to
`namespace` to preserve existing namespaced properties.
If the first token in the namespace string is "YAHOO", the token is
discarded.
Be careful with namespace tokens. Reserved words may work in some browsers
and not others. For instance, the following will fail in some browsers
because the supported version of JavaScript reserves the word "long":
Y.namespace("really.long.nested.namespace");
<em>Note: If you pass multiple arguments to create multiple namespaces, only
the last one created is returned from this function.</em>
@method namespace
@param {String} namespace* namespaces to create.
@return {Object} A reference to the last namespace object created.
**/
namespace: function() {
var a = arguments, o, i = 0, j, d, arg;
for (; i < a.length; i++) {
o = this; //Reset base object per argument or it will get reused from the last
arg = a[i];
if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present
d = arg.split(PERIOD);
for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
} else {
o[arg] = o[arg] || {};
o = o[arg]; //Reset base object to the new object so it's returned
}
}
return o;
},
// this is replaced if the log module is included
log: NOOP,
message: NOOP,
// this is replaced if the dump module is included
dump: function (o) { return ''+o; },
/**
* Report an error. The reporting mechanism is controlled by
* the `throwFail` configuration attribute. If throwFail is
* not specified, the message is written to the Logger, otherwise
* a JS error is thrown. If an `errorFn` is specified in the config
* it must return `true` to keep the error from being thrown.
* @method error
* @param msg {String} the error message.
* @param e {Error|String} Optional JS error that was caught, or an error string.
* @param src Optional additional info (passed to `Y.config.errorFn` and `Y.message`)
* and `throwFail` is specified, this error will be re-thrown.
* @return {YUI} this YUI instance.
*/
error: function(msg, e, src) {
//TODO Add check for window.onerror here
var Y = this, ret;
if (Y.config.errorFn) {
ret = Y.config.errorFn.apply(Y, arguments);
}
if (Y.config.throwFail && !ret) {
throw (e || new Error(msg));
} else {
Y.message(msg, 'error', ''+src); // don't scrub this one
}
return Y;
},
/**
* Generate an id that is unique among all YUI instances
* @method guid
* @param pre {String} optional guid prefix.
* @return {String} the guid.
*/
guid: function(pre) {
var id = this.Env._guidp + '_' + (++this.Env._uidx);
return (pre) ? (pre + id) : id;
},
/**
* Returns a `guid` associated with an object. If the object
* does not have one, a new one is created unless `readOnly`
* is specified.
* @method stamp
* @param o {Object} The object to stamp.
* @param readOnly {Boolean} if `true`, a valid guid will only
* be returned if the object has one assigned to it.
* @return {String} The object's guid or null.
*/
stamp: function(o, readOnly) {
var uid;
if (!o) {
return o;
}
// IE generates its own unique ID for dom nodes
// The uniqueID property of a document node returns a new ID
if (o.uniqueID && o.nodeType && o.nodeType !== 9) {
uid = o.uniqueID;
} else {
uid = (typeof o === 'string') ? o : o._yuid;
}
if (!uid) {
uid = this.guid();
if (!readOnly) {
try {
o._yuid = uid;
} catch (e) {
uid = null;
}
}
}
return uid;
},
/**
* Destroys the YUI instance
* @method destroy
* @since 3.3.0
*/
destroy: function() {
var Y = this;
if (Y.Event) {
Y.Event._unload();
}
delete instances[Y.id];
delete Y.Env;
delete Y.config;
}
/**
* instanceof check for objects that works around
* memory leak in IE when the item tested is
* window/document
* @method instanceOf
* @param o {Object} The object to check.
* @param type {Object} The class to check against.
* @since 3.3.0
*/
};
YUI.prototype = proto;
// inheritance utilities are not available yet
for (prop in proto) {
if (proto.hasOwnProperty(prop)) {
YUI[prop] = proto[prop];
}
}
/**
Static method on the Global YUI object to apply a config to all YUI instances.
It's main use case is "mashups" where several third party scripts are trying to write to
a global YUI config at the same time. This way they can all call `YUI.applyConfig({})` instead of
overwriting other scripts configs.
@static
@since 3.5.0
@method applyConfig
@param {Object} o the configuration object.
@example
YUI.applyConfig({
modules: {
davglass: {
fullpath: './davglass.js'
}
}
});
YUI.applyConfig({
modules: {
foo: {
fullpath: './foo.js'
}
}
});
YUI().use('davglass', function(Y) {
//Module davglass will be available here..
});
*/
YUI.applyConfig = function(o) {
if (!o) {
return;
}
//If there is a GlobalConfig, apply it first to set the defaults
if (YUI.GlobalConfig) {
this.prototype.applyConfig.call(this, YUI.GlobalConfig);
}
//Apply this config to it
this.prototype.applyConfig.call(this, o);
//Reset GlobalConfig to the combined config
YUI.GlobalConfig = this.config;
};
// set up the environment
YUI._init();
if (hasWin) {
// add a window load event at load time so we can capture
// the case where it fires before dynamic loading is
// complete.
add(window, 'load', handleLoad);
} else {
handleLoad();
}
YUI.Env.add = add;
YUI.Env.remove = remove;
/*global exports*/
// Support the CommonJS method for exporting our single global
if (typeof exports == 'object') {
exports.YUI = YUI;
}
}());
/**
* The config object contains all of the configuration options for
* the `YUI` instance. This object is supplied by the implementer
* when instantiating a `YUI` instance. Some properties have default
* values if they are not supplied by the implementer. This should
* not be updated directly because some values are cached. Use
* `applyConfig()` to update the config object on a YUI instance that
* has already been configured.
*
* @class config
* @static
*/
/**
* Allows the YUI seed file to fetch the loader component and library
* metadata to dynamically load additional dependencies.
*
* @property bootstrap
* @type boolean
* @default true
*/
/**
* Turns on writing Ylog messages to the browser console.
*
* @property debug
* @type boolean
* @default true
*/
/**
* Log to the browser console if debug is on and the browser has a
* supported console.
*
* @property useBrowserConsole
* @type boolean
* @default true
*/
/**
* A hash of log sources that should be logged. If specified, only
* log messages from these sources will be logged.
*
* @property logInclude
* @type object
*/
/**
* A hash of log sources that should be not be logged. If specified,
* all sources are logged if not on this list.
*
* @property logExclude
* @type object
*/
/**
* Set to true if the yui seed file was dynamically loaded in
* order to bootstrap components relying on the window load event
* and the `domready` custom event.
*
* @property injected
* @type boolean
* @default false
*/
/**
* If `throwFail` is set, `Y.error` will generate or re-throw a JS Error.
* Otherwise the failure is logged.
*
* @property throwFail
* @type boolean
* @default true
*/
/**
* The window/frame that this instance should operate in.
*
* @property win
* @type Window
* @default the window hosting YUI
*/
/**
* The document associated with the 'win' configuration.
*
* @property doc
* @type Document
* @default the document hosting YUI
*/
/**
* A list of modules that defines the YUI core (overrides the default list).
*
* @property core
* @type Array
* @default [ get,features,intl-base,yui-log,yui-later,loader-base, loader-rollup, loader-yui3 ]
*/
/**
* A list of languages in order of preference. This list is matched against
* the list of available languages in modules that the YUI instance uses to
* determine the best possible localization of language sensitive modules.
* Languages are represented using BCP 47 language tags, such as "en-GB" for
* English as used in the United Kingdom, or "zh-Hans-CN" for simplified
* Chinese as used in China. The list can be provided as a comma-separated
* list or as an array.
*
* @property lang
* @type string|string[]
*/
/**
* The default date format
* @property dateFormat
* @type string
* @deprecated use configuration in `DataType.Date.format()` instead.
*/
/**
* The default locale
* @property locale
* @type string
* @deprecated use `config.lang` instead.
*/
/**
* The default interval when polling in milliseconds.
* @property pollInterval
* @type int
* @default 20
*/
/**
* The number of dynamic nodes to insert by default before
* automatically removing them. This applies to script nodes
* because removing the node will not make the evaluated script
* unavailable. Dynamic CSS is not auto purged, because removing
* a linked style sheet will also remove the style definitions.
* @property purgethreshold
* @type int
* @default 20
*/
/**
* The default interval when polling in milliseconds.
* @property windowResizeDelay
* @type int
* @default 40
*/
/**
* Base directory for dynamic loading
* @property base
* @type string
*/
/*
* The secure base dir (not implemented)
* For dynamic loading.
* @property secureBase
* @type string
*/
/**
* The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?`
* For dynamic loading.
* @property comboBase
* @type string
*/
/**
* The root path to prepend to module path for the combo service.
* Ex: 3.0.0b1/build/
* For dynamic loading.
* @property root
* @type string
*/
/**
* A filter to apply to result urls. This filter will modify the default
* path for all modules. The default path for the YUI library is the
* minified version of the files (e.g., event-min.js). The filter property
* can be a predefined filter or a custom filter. The valid predefined
* filters are:
* <dl>
* <dt>DEBUG</dt>
* <dd>Selects the debug versions of the library (e.g., event-debug.js).
* This option will automatically include the Logger widget</dd>
* <dt>RAW</dt>
* <dd>Selects the non-minified version of the library (e.g., event.js).</dd>
* </dl>
* You can also define a custom filter, which must be an object literal
* containing a search expression and a replace string:
*
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
*
* For dynamic loading.
*
* @property filter
* @type string|object
*/
/**
* The `skin` config let's you configure application level skin
* customizations. It contains the following attributes which
* can be specified to override the defaults:
*
* // The default skin, which is automatically applied if not
* // overriden by a component-specific skin definition.
* // Change this in to apply a different skin globally
* defaultSkin: 'sam',
*
* // This is combined with the loader base property to get
* // the default root directory for a skin.
* base: 'assets/skins/',
*
* // Any component-specific overrides can be specified here,
* // making it possible to load different skins for different
* // components. It is possible to load more than one skin
* // for a given component as well.
* overrides: {
* slider: ['capsule', 'round']
* }
*
* For dynamic loading.
*
* @property skin
*/
/**
* Hash of per-component filter specification. If specified for a given
* component, this overrides the filter config.
*
* For dynamic loading.
*
* @property filters
*/
/**
* Use the YUI combo service to reduce the number of http connections
* required to load your dependencies. Turning this off will
* disable combo handling for YUI and all module groups configured
* with a combo service.
*
* For dynamic loading.
*
* @property combine
* @type boolean
* @default true if 'base' is not supplied, false if it is.
*/
/**
* A list of modules that should never be dynamically loaded
*
* @property ignore
* @type string[]
*/
/**
* A list of modules that should always be loaded when required, even if already
* present on the page.
*
* @property force
* @type string[]
*/
/**
* Node or id for a node that should be used as the insertion point for new
* nodes. For dynamic loading.
*
* @property insertBefore
* @type string
*/
/**
* Object literal containing attributes to add to dynamically loaded script
* nodes.
* @property jsAttributes
* @type string
*/
/**
* Object literal containing attributes to add to dynamically loaded link
* nodes.
* @property cssAttributes
* @type string
*/
/**
* Number of milliseconds before a timeout occurs when dynamically
* loading nodes. If not set, there is no timeout.
* @property timeout
* @type int
*/
/**
* Callback for the 'CSSComplete' event. When dynamically loading YUI
* components with CSS, this property fires when the CSS is finished
* loading but script loading is still ongoing. This provides an
* opportunity to enhance the presentation of a loading page a little
* bit before the entire loading process is done.
*
* @property onCSS
* @type function
*/
/**
* A hash of module definitions to add to the list of YUI components.
* These components can then be dynamically loaded side by side with
* YUI via the `use()` method. This is a hash, the key is the module
* name, and the value is an object literal specifying the metdata
* for the module. See `Loader.addModule` for the supported module
* metadata fields. Also see groups, which provides a way to
* configure the base and combo spec for a set of modules.
*
* modules: {
* mymod1: {
* requires: ['node'],
* fullpath: '/mymod1/mymod1.js'
* },
* mymod2: {
* requires: ['mymod1'],
* fullpath: '/mymod2/mymod2.js'
* },
* mymod3: '/js/mymod3.js',
* mycssmod: '/css/mycssmod.css'
* }
*
*
* @property modules
* @type object
*/
/**
* Aliases are dynamic groups of modules that can be used as
* shortcuts.
*
* YUI({
* aliases: {
* davglass: [ 'node', 'yql', 'dd' ],
* mine: [ 'davglass', 'autocomplete']
* }
* }).use('mine', function(Y) {
* //Node, YQL, DD & AutoComplete available here..
* });
*
* @property aliases
* @type object
*/
/**
* A hash of module group definitions. It for each group you
* can specify a list of modules and the base path and
* combo spec to use when dynamically loading the modules.
*
* groups: {
* yui2: {
* // specify whether or not this group has a combo service
* combine: true,
*
* // The comboSeperator to use with this group's combo handler
* comboSep: ';',
*
* // The maxURLLength for this server
* maxURLLength: 500,
*
* // the base path for non-combo paths
* base: 'http://yui.yahooapis.com/2.8.0r4/build/',
*
* // the path to the combo service
* comboBase: 'http://yui.yahooapis.com/combo?',
*
* // a fragment to prepend to the path attribute when
* // when building combo urls
* root: '2.8.0r4/build/',
*
* // the module definitions
* modules: {
* yui2_yde: {
* path: "yahoo-dom-event/yahoo-dom-event.js"
* },
* yui2_anim: {
* path: "animation/animation.js",
* requires: ['yui2_yde']
* }
* }
* }
* }
*
* @property groups
* @type object
*/
/**
* The loader 'path' attribute to the loader itself. This is combined
* with the 'base' attribute to dynamically load the loader component
* when boostrapping with the get utility alone.
*
* @property loaderPath
* @type string
* @default loader/loader-min.js
*/
/**
* Specifies whether or not YUI().use(...) will attempt to load CSS
* resources at all. Any truthy value will cause CSS dependencies
* to load when fetching script. The special value 'force' will
* cause CSS dependencies to be loaded even if no script is needed.
*
* @property fetchCSS
* @type boolean|string
* @default true
*/
/**
* The default gallery version to build gallery module urls
* @property gallery
* @type string
* @since 3.1.0
*/
/**
* The default YUI 2 version to build yui2 module urls. This is for
* intrinsic YUI 2 support via the 2in3 project. Also see the '2in3'
* config for pulling different revisions of the wrapped YUI 2
* modules.
* @since 3.1.0
* @property yui2
* @type string
* @default 2.9.0
*/
/**
* The 2in3 project is a deployment of the various versions of YUI 2
* deployed as first-class YUI 3 modules. Eventually, the wrapper
* for the modules will change (but the underlying YUI 2 code will
* be the same), and you can select a particular version of
* the wrapper modules via this config.
* @since 3.1.0
* @property 2in3
* @type string
* @default 4
*/
/**
* Alternative console log function for use in environments without
* a supported native console. The function is executed in the
* YUI instance context.
* @since 3.1.0
* @property logFn
* @type Function
*/
/**
* A callback to execute when Y.error is called. It receives the
* error message and an javascript error object if Y.error was
* executed because a javascript error was caught. The function
* is executed in the YUI instance context. Returning `true` from this
* function will stop the Error from being thrown.
*
* @since 3.2.0
* @property errorFn
* @type Function
*/
/**
* A callback to execute when the loader fails to load one or
* more resource. This could be because of a script load
* failure. It can also fail if a javascript module fails
* to register itself, but only when the 'requireRegistration'
* is true. If this function is defined, the use() callback will
* only be called when the loader succeeds, otherwise it always
* executes unless there was a javascript error when attaching
* a module.
*
* @since 3.3.0
* @property loadErrorFn
* @type Function
*/
/**
* When set to true, the YUI loader will expect that all modules
* it is responsible for loading will be first-class YUI modules
* that register themselves with the YUI global. If this is
* set to true, loader will fail if the module registration fails
* to happen after the script is loaded.
*
* @since 3.3.0
* @property requireRegistration
* @type boolean
* @default false
*/
/**
* Cache serviced use() requests.
* @since 3.3.0
* @property cacheUse
* @type boolean
* @default true
* @deprecated no longer used
*/
/**
* Whether or not YUI should use native ES5 functionality when available for
* features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will
* always use its own fallback implementations instead of relying on ES5
* functionality, even when it's available.
*
* @method useNativeES5
* @type Boolean
* @default true
* @since 3.5.0
*/
YUI.add('yui-base', function(Y) {
/*
* YUI stub
* @module yui
* @submodule yui-base
*/
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* Provides core language utilites and extensions used throughout YUI.
*
* @class Lang
* @static
*/
var L = Y.Lang || (Y.Lang = {}),
STRING_PROTO = String.prototype,
TOSTRING = Object.prototype.toString,
TYPES = {
'undefined' : 'undefined',
'number' : 'number',
'boolean' : 'boolean',
'string' : 'string',
'[object Function]': 'function',
'[object RegExp]' : 'regexp',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object Error]' : 'error'
},
SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g,
TRIMREGEX = /^\s+|\s+$/g,
NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i;
// -- Protected Methods --------------------------------------------------------
/**
Returns `true` if the given function appears to be implemented in native code,
`false` otherwise. Will always return `false` -- even in ES5-capable browsers --
if the `useNativeES5` YUI config option is set to `false`.
This isn't guaranteed to be 100% accurate and won't work for anything other than
functions, but it can be useful for determining whether a function like
`Array.prototype.forEach` is native or a JS shim provided by another library.
There's a great article by @kangax discussing certain flaws with this technique:
<http://perfectionkills.com/detecting-built-in-host-methods/>
While his points are valid, it's still possible to benefit from this function
as long as it's used carefully and sparingly, and in such a way that false
negatives have minimal consequences. It's used internally to avoid using
potentially broken non-native ES5 shims that have been added to the page by
other libraries.
@method _isNative
@param {Function} fn Function to test.
@return {Boolean} `true` if _fn_ appears to be native, `false` otherwise.
@static
@protected
@since 3.5.0
**/
L._isNative = function (fn) {
return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn));
};
// -- Public Methods -----------------------------------------------------------
/**
* Determines whether or not the provided item is an array.
*
* Returns `false` for array-like collections such as the function `arguments`
* collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to
* test for an array-like collection.
*
* @method isArray
* @param o The object to test.
* @return {boolean} true if o is an array.
* @static
*/
L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) {
return L.type(o) === 'array';
};
/**
* Determines whether or not the provided item is a boolean.
* @method isBoolean
* @static
* @param o The object to test.
* @return {boolean} true if o is a boolean.
*/
L.isBoolean = function(o) {
return typeof o === 'boolean';
};
/**
* Determines whether or not the supplied item is a date instance.
* @method isDate
* @static
* @param o The object to test.
* @return {boolean} true if o is a date.
*/
L.isDate = function(o) {
return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o);
};
/**
* <p>
* Determines whether or not the provided item is a function.
* Note: Internet Explorer thinks certain functions are objects:
* </p>
*
* <pre>
* var obj = document.createElement("object");
* Y.Lang.isFunction(obj.getAttribute) // reports false in IE
*
* var input = document.createElement("input"); // append to body
* Y.Lang.isFunction(input.focus) // reports false in IE
* </pre>
*
* <p>
* You will have to implement additional tests if these functions
* matter to you.
* </p>
*
* @method isFunction
* @static
* @param o The object to test.
* @return {boolean} true if o is a function.
*/
L.isFunction = function(o) {
return L.type(o) === 'function';
};
/**
* Determines whether or not the provided item is null.
* @method isNull
* @static
* @param o The object to test.
* @return {boolean} true if o is null.
*/
L.isNull = function(o) {
return o === null;
};
/**
* Determines whether or not the provided item is a legal number.
* @method isNumber
* @static
* @param o The object to test.
* @return {boolean} true if o is a number.
*/
L.isNumber = function(o) {
return typeof o === 'number' && isFinite(o);
};
/**
* Determines whether or not the provided item is of type object
* or function. Note that arrays are also objects, so
* <code>Y.Lang.isObject([]) === true</code>.
* @method isObject
* @static
* @param o The object to test.
* @param failfn {boolean} fail if the input is a function.
* @return {boolean} true if o is an object.
* @see isPlainObject
*/
L.isObject = function(o, failfn) {
var t = typeof o;
return (o && (t === 'object' ||
(!failfn && (t === 'function' || L.isFunction(o))))) || false;
};
/**
* Determines whether or not the provided item is a string.
* @method isString
* @static
* @param o The object to test.
* @return {boolean} true if o is a string.
*/
L.isString = function(o) {
return typeof o === 'string';
};
/**
* Determines whether or not the provided item is undefined.
* @method isUndefined
* @static
* @param o The object to test.
* @return {boolean} true if o is undefined.
*/
L.isUndefined = function(o) {
return typeof o === 'undefined';
};
/**
* A convenience method for detecting a legitimate non-null value.
* Returns false for null/undefined/NaN, true for other values,
* including 0/false/''
* @method isValue
* @static
* @param o The item to test.
* @return {boolean} true if it is not null/undefined/NaN || false.
*/
L.isValue = function(o) {
var t = L.type(o);
switch (t) {
case 'number':
return isFinite(o);
case 'null': // fallthru
case 'undefined':
return false;
default:
return !!t;
}
};
/**
* Returns the current time in milliseconds.
*
* @method now
* @return {Number} Current time in milliseconds.
* @static
* @since 3.3.0
*/
L.now = Date.now || function () {
return new Date().getTime();
};
/**
* Lightweight version of <code>Y.substitute</code>. Uses the same template
* structure as <code>Y.substitute</code>, but doesn't support recursion,
* auto-object coersion, or formats.
* @method sub
* @param {string} s String to be modified.
* @param {object} o Object containing replacement values.
* @return {string} the substitute result.
* @static
* @since 3.2.0
*/
L.sub = function(s, o) {
return s.replace ? s.replace(SUBREGEX, function (match, key) {
return L.isUndefined(o[key]) ? match : o[key];
}) : s;
};
/**
* Returns a string without any leading or trailing whitespace. If
* the input is not a string, the input will be returned untouched.
* @method trim
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trim = STRING_PROTO.trim ? function(s) {
return s && s.trim ? s.trim() : s;
} : function (s) {
try {
return s.replace(TRIMREGEX, '');
} catch (e) {
return s;
}
};
/**
* Returns a string without any leading whitespace.
* @method trimLeft
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trimLeft = STRING_PROTO.trimLeft ? function (s) {
return s.trimLeft();
} : function (s) {
return s.replace(/^\s+/, '');
};
/**
* Returns a string without any trailing whitespace.
* @method trimRight
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trimRight = STRING_PROTO.trimRight ? function (s) {
return s.trimRight();
} : function (s) {
return s.replace(/\s+$/, '');
};
/**
Returns one of the following strings, representing the type of the item passed
in:
* "array"
* "boolean"
* "date"
* "error"
* "function"
* "null"
* "number"
* "object"
* "regexp"
* "string"
* "undefined"
Known issues:
* `typeof HTMLElementCollection` returns function in Safari, but
`Y.Lang.type()` reports "object", which could be a good thing --
but it actually caused the logic in <code>Y.Lang.isObject</code> to fail.
@method type
@param o the item to test.
@return {string} the detected type.
@static
**/
L.type = function(o) {
return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};
/**
@module yui
@submodule yui-base
*/
var Lang = Y.Lang,
Native = Array.prototype,
hasOwn = Object.prototype.hasOwnProperty;
/**
Provides utility methods for working with arrays. Additional array helpers can
be found in the `collection` and `array-extras` modules.
`Y.Array(thing)` returns a native array created from _thing_. Depending on
_thing_'s type, one of the following will happen:
* Arrays are returned unmodified unless a non-zero _startIndex_ is
specified.
* Array-like collections (see `Array.test()`) are converted to arrays.
* For everything else, a new array is created with _thing_ as the sole
item.
Note: elements that are also collections, such as `<form>` and `<select>`
elements, are not automatically converted to arrays. To force a conversion,
pass `true` as the value of the _force_ parameter.
@class Array
@constructor
@param {Any} thing The thing to arrayify.
@param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like
collection, a subset of items starting at the specified index will be
returned.
@param {Boolean} [force=false] If `true`, _thing_ will be treated as an
array-like collection no matter what.
@return {Array} A native array created from _thing_, according to the rules
described above.
**/
function YArray(thing, startIndex, force) {
var len, result;
startIndex || (startIndex = 0);
if (force || YArray.test(thing)) {
// IE throws when trying to slice HTMLElement collections.
try {
return Native.slice.call(thing, startIndex);
} catch (ex) {
result = [];
for (len = thing.length; startIndex < len; ++startIndex) {
result.push(thing[startIndex]);
}
return result;
}
}
return [thing];
}
Y.Array = YArray;
/**
Dedupes an array of strings, returning an array that's guaranteed to contain
only one copy of a given string.
This method differs from `Array.unique()` in that it's optimized for use only
with strings, whereas `unique` may be used with other types (but is slower).
Using `dedupe()` with non-string values may result in unexpected behavior.
@method dedupe
@param {String[]} array Array of strings to dedupe.
@return {Array} Deduped copy of _array_.
@static
@since 3.4.0
**/
YArray.dedupe = function (array) {
var hash = {},
results = [],
i, item, len;
for (i = 0, len = array.length; i < len; ++i) {
item = array[i];
if (!hasOwn.call(hash, item)) {
hash[item] = 1;
results.push(item);
}
}
return results;
};
/**
Executes the supplied function on each item in the array. This method wraps
the native ES5 `Array.forEach()` method if available.
@method each
@param {Array} array Array to iterate.
@param {Function} fn Function to execute on each item in the array. The function
will receive the following arguments:
@param {Any} fn.item Current array item.
@param {Number} fn.index Current array index.
@param {Array} fn.array Array being iterated.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {YUI} The YUI instance.
@static
**/
YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) {
Native.forEach.call(array || [], fn, thisObj || Y);
return Y;
} : function (array, fn, thisObj) {
for (var i = 0, len = (array && array.length) || 0; i < len; ++i) {
if (i in array) {
fn.call(thisObj || Y, array[i], i, array);
}
}
return Y;
};
/**
Alias for `each()`.
@method forEach
@static
**/
/**
Returns an object using the first array as keys and the second as values. If
the second array is not provided, or if it doesn't contain the same number of
values as the first array, then `true` will be used in place of the missing
values.
@example
Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']);
// => {a: 'foo', b: 'bar', c: true}
@method hash
@param {String[]} keys Array of strings to use as keys.
@param {Array} [values] Array to use as values.
@return {Object} Hash using the first array as keys and the second as values.
@static
**/
YArray.hash = function (keys, values) {
var hash = {},
vlen = (values && values.length) || 0,
i, len;
for (i = 0, len = keys.length; i < len; ++i) {
if (i in keys) {
hash[keys[i]] = vlen > i && i in values ? values[i] : true;
}
}
return hash;
};
/**
Returns the index of the first item in the array that's equal (using a strict
equality check) to the specified _value_, or `-1` if the value isn't found.
This method wraps the native ES5 `Array.indexOf()` method if available.
@method indexOf
@param {Array} array Array to search.
@param {Any} value Value to search for.
@param {Number} [from=0] The index at which to begin the search.
@return {Number} Index of the item strictly equal to _value_, or `-1` if not
found.
@static
**/
YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) {
return Native.indexOf.call(array, value, from);
} : function (array, value, from) {
// http://es5.github.com/#x15.4.4.14
var len = array.length;
from = +from || 0;
from = (from > 0 || -1) * Math.floor(Math.abs(from));
if (from < 0) {
from += len;
if (from < 0) {
from = 0;
}
}
for (; from < len; ++from) {
if (from in array && array[from] === value) {
return from;
}
}
return -1;
};
/**
Numeric sort convenience function.
The native `Array.prototype.sort()` function converts values to strings and
sorts them in lexicographic order, which is unsuitable for sorting numeric
values. Provide `Array.numericSort` as a custom sort function when you want
to sort values in numeric order.
@example
[42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort);
// => [4, 8, 15, 16, 23, 42]
@method numericSort
@param {Number} a First value to compare.
@param {Number} b Second value to compare.
@return {Number} Difference between _a_ and _b_.
@static
**/
YArray.numericSort = function (a, b) {
return a - b;
};
/**
Executes the supplied function on each item in the array. Returning a truthy
value from the function will stop the processing of remaining items.
@method some
@param {Array} array Array to iterate over.
@param {Function} fn Function to execute on each item. The function will receive
the following arguments:
@param {Any} fn.value Current array item.
@param {Number} fn.index Current array index.
@param {Array} fn.array Array being iterated over.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {Boolean} `true` if the function returns a truthy value on any of the
items in the array; `false` otherwise.
@static
**/
YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) {
return Native.some.call(array, fn, thisObj);
} : function (array, fn, thisObj) {
for (var i = 0, len = array.length; i < len; ++i) {
if (i in array && fn.call(thisObj, array[i], i, array)) {
return true;
}
}
return false;
};
/**
Evaluates _obj_ to determine if it's an array, an array-like collection, or
something else. This is useful when working with the function `arguments`
collection and `HTMLElement` collections.
Note: This implementation doesn't consider elements that are also
collections, such as `<form>` and `<select>`, to be array-like.
@method test
@param {Object} obj Object to test.
@return {Number} A number indicating the results of the test:
* 0: Neither an array nor an array-like collection.
* 1: Real array.
* 2: Array-like collection.
@static
**/
YArray.test = function (obj) {
var result = 0;
if (Lang.isArray(obj)) {
result = 1;
} else if (Lang.isObject(obj)) {
try {
// indexed, but no tagName (element) or alert (window),
// or functions without apply/call (Safari
// HTMLElementCollection bug).
if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) {
result = 2;
}
} catch (ex) {}
}
return result;
};
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* A simple FIFO queue. Items are added to the Queue with add(1..n items) and
* removed using next().
*
* @class Queue
* @constructor
* @param {MIXED} item* 0..n items to seed the queue.
*/
function Queue() {
this._init();
this.add.apply(this, arguments);
}
Queue.prototype = {
/**
* Initialize the queue
*
* @method _init
* @protected
*/
_init: function() {
/**
* The collection of enqueued items
*
* @property _q
* @type Array
* @protected
*/
this._q = [];
},
/**
* Get the next item in the queue. FIFO support
*
* @method next
* @return {MIXED} the next item in the queue.
*/
next: function() {
return this._q.shift();
},
/**
* Get the last in the queue. LIFO support.
*
* @method last
* @return {MIXED} the last item in the queue.
*/
last: function() {
return this._q.pop();
},
/**
* Add 0..n items to the end of the queue.
*
* @method add
* @param {MIXED} item* 0..n items.
* @return {object} this queue.
*/
add: function() {
this._q.push.apply(this._q, arguments);
return this;
},
/**
* Returns the current number of queued items.
*
* @method size
* @return {Number} The size.
*/
size: function() {
return this._q.length;
}
};
Y.Queue = Queue;
YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue();
/**
The YUI module contains the components required for building the YUI seed file.
This includes the script loading mechanism, a simple queue, and the core
utilities for the library.
@module yui
@submodule yui-base
**/
var CACHED_DELIMITER = '__',
hasOwn = Object.prototype.hasOwnProperty,
isObject = Y.Lang.isObject;
/**
Returns a wrapper for a function which caches the return value of that function,
keyed off of the combined string representation of the argument values provided
when the wrapper is called.
Calling this function again with the same arguments will return the cached value
rather than executing the wrapped function.
Note that since the cache is keyed off of the string representation of arguments
passed to the wrapper function, arguments that aren't strings and don't provide
a meaningful `toString()` method may result in unexpected caching behavior. For
example, the objects `{}` and `{foo: 'bar'}` would both be converted to the
string `[object Object]` when used as a cache key.
@method cached
@param {Function} source The function to memoize.
@param {Object} [cache={}] Object in which to store cached values. You may seed
this object with pre-existing cached values if desired.
@param {any} [refetch] If supplied, this value is compared with the cached value
using a `==` comparison. If the values are equal, the wrapped function is
executed again even though a cached value exists.
@return {Function} Wrapped function.
@for YUI
**/
Y.cached = function (source, cache, refetch) {
cache || (cache = {});
return function (arg) {
var key = arguments.length > 1 ?
Array.prototype.join.call(arguments, CACHED_DELIMITER) :
String(arg);
if (!(key in cache) || (refetch && cache[key] == refetch)) {
cache[key] = source.apply(source, arguments);
}
return cache[key];
};
};
/**
Returns the `location` object from the window/frame in which this YUI instance
operates, or `undefined` when executing in a non-browser environment
(e.g. Node.js).
It is _not_ recommended to hold references to the `window.location` object
outside of the scope of a function in which its properties are being accessed or
its methods are being called. This is because of a nasty bug/issue that exists
in both Safari and MobileSafari browsers:
[WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679).
@method getLocation
@return {location} The `location` object from the window/frame in which this YUI
instance operates.
@since 3.5.0
**/
Y.getLocation = function () {
// It is safer to look this up every time because yui-base is attached to a
// YUI instance before a user's config is applied; i.e. `Y.config.win` does
// not point the correct window object when this file is loaded.
var win = Y.config.win;
// It is not safe to hold a reference to the `location` object outside the
// scope in which it is being used. The WebKit engine used in Safari and
// MobileSafari will "disconnect" the `location` object from the `window`
// when a page is restored from back/forward history cache.
return win && win.location;
};
/**
Returns a new object containing all of the properties of all the supplied
objects. The properties from later objects will overwrite those in earlier
objects.
Passing in a single object will create a shallow copy of it. For a deep copy,
use `clone()`.
@method merge
@param {Object} objects* One or more objects to merge.
@return {Object} A new merged object.
**/
Y.merge = function () {
var args = arguments,
i = 0,
len = args.length,
result = {};
for (; i < len; ++i) {
Y.mix(result, args[i], true);
}
return result;
};
/**
Mixes _supplier_'s properties into _receiver_.
Properties on _receiver_ or _receiver_'s prototype will not be overwritten or
shadowed unless the _overwrite_ parameter is `true`, and will not be merged
unless the _merge_ parameter is `true`.
In the default mode (0), only properties the supplier owns are copied (prototype
properties are not copied). The following copying modes are available:
* `0`: _Default_. Object to object.
* `1`: Prototype to prototype.
* `2`: Prototype to prototype and object to object.
* `3`: Prototype to object.
* `4`: Object to prototype.
@method mix
@param {Function|Object} receiver The object or function to receive the mixed
properties.
@param {Function|Object} supplier The object or function supplying the
properties to be mixed.
@param {Boolean} [overwrite=false] If `true`, properties that already exist
on the receiver will be overwritten with properties from the supplier.
@param {String[]} [whitelist] An array of property names to copy. If
specified, only the whitelisted properties will be copied, and all others
will be ignored.
@param {Number} [mode=0] Mix mode to use. See above for available modes.
@param {Boolean} [merge=false] If `true`, objects and arrays that already
exist on the receiver will have the corresponding object/array from the
supplier merged into them, rather than being skipped or overwritten. When
both _overwrite_ and _merge_ are `true`, _merge_ takes precedence.
@return {Function|Object|YUI} The receiver, or the YUI instance if the
specified receiver is falsy.
**/
Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) {
var alwaysOverwrite, exists, from, i, key, len, to;
// If no supplier is given, we return the receiver. If no receiver is given,
// we return Y. Returning Y doesn't make much sense to me, but it's
// grandfathered in for backcompat reasons.
if (!receiver || !supplier) {
return receiver || Y;
}
if (mode) {
// In mode 2 (prototype to prototype and object to object), we recurse
// once to do the proto to proto mix. The object to object mix will be
// handled later on.
if (mode === 2) {
Y.mix(receiver.prototype, supplier.prototype, overwrite,
whitelist, 0, merge);
}
// Depending on which mode is specified, we may be copying from or to
// the prototypes of the supplier and receiver.
from = mode === 1 || mode === 3 ? supplier.prototype : supplier;
to = mode === 1 || mode === 4 ? receiver.prototype : receiver;
// If either the supplier or receiver doesn't actually have a
// prototype property, then we could end up with an undefined `from`
// or `to`. If that happens, we abort and return the receiver.
if (!from || !to) {
return receiver;
}
} else {
from = supplier;
to = receiver;
}
// If `overwrite` is truthy and `merge` is falsy, then we can skip a
// property existence check on each iteration and save some time.
alwaysOverwrite = overwrite && !merge;
if (whitelist) {
for (i = 0, len = whitelist.length; i < len; ++i) {
key = whitelist[i];
// We call `Object.prototype.hasOwnProperty` instead of calling
// `hasOwnProperty` on the object itself, since the object's
// `hasOwnProperty` method may have been overridden or removed.
// Also, some native objects don't implement a `hasOwnProperty`
// method.
if (!hasOwn.call(from, key)) {
continue;
}
// The `key in to` check here is (sadly) intentional for backwards
// compatibility reasons. It prevents undesired shadowing of
// prototype members on `to`.
exists = alwaysOverwrite ? false : key in to;
if (merge && exists && isObject(to[key], true)
&& isObject(from[key], true)) {
// If we're in merge mode, and the key is present on both
// objects, and the value on both objects is either an object or
// an array (but not a function), then we recurse to merge the
// `from` value into the `to` value instead of overwriting it.
//
// Note: It's intentional that the whitelist isn't passed to the
// recursive call here. This is legacy behavior that lots of
// code still depends on.
Y.mix(to[key], from[key], overwrite, null, 0, merge);
} else if (overwrite || !exists) {
// We're not in merge mode, so we'll only copy the `from` value
// to the `to` value if we're in overwrite mode or if the
// current key doesn't exist on the `to` object.
to[key] = from[key];
}
}
} else {
for (key in from) {
// The code duplication here is for runtime performance reasons.
// Combining whitelist and non-whitelist operations into a single
// loop or breaking the shared logic out into a function both result
// in worse performance, and Y.mix is critical enough that the byte
// tradeoff is worth it.
if (!hasOwn.call(from, key)) {
continue;
}
// The `key in to` check here is (sadly) intentional for backwards
// compatibility reasons. It prevents undesired shadowing of
// prototype members on `to`.
exists = alwaysOverwrite ? false : key in to;
if (merge && exists && isObject(to[key], true)
&& isObject(from[key], true)) {
Y.mix(to[key], from[key], overwrite, null, 0, merge);
} else if (overwrite || !exists) {
to[key] = from[key];
}
}
// If this is an IE browser with the JScript enumeration bug, force
// enumeration of the buggy properties by making a recursive call with
// the buggy properties as the whitelist.
if (Y.Object._hasEnumBug) {
Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge);
}
}
return receiver;
};
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* Adds utilities to the YUI instance for working with objects.
*
* @class Object
*/
var Lang = Y.Lang,
hasOwn = Object.prototype.hasOwnProperty,
UNDEFINED, // <-- Note the comma. We're still declaring vars.
/**
* Returns a new object that uses _obj_ as its prototype. This method wraps the
* native ES5 `Object.create()` method if available, but doesn't currently
* pass through `Object.create()`'s second argument (properties) in order to
* ensure compatibility with older browsers.
*
* @method ()
* @param {Object} obj Prototype object.
* @return {Object} New object using _obj_ as its prototype.
* @static
*/
O = Y.Object = Lang._isNative(Object.create) ? function (obj) {
// We currently wrap the native Object.create instead of simply aliasing it
// to ensure consistency with our fallback shim, which currently doesn't
// support Object.create()'s second argument (properties). Once we have a
// safe fallback for the properties arg, we can stop wrapping
// Object.create().
return Object.create(obj);
} : (function () {
// Reusable constructor function for the Object.create() shim.
function F() {}
// The actual shim.
return function (obj) {
F.prototype = obj;
return new F();
};
}()),
/**
* Property names that IE doesn't enumerate in for..in loops, even when they
* should be enumerable. When `_hasEnumBug` is `true`, it's necessary to
* manually enumerate these properties.
*
* @property _forceEnum
* @type String[]
* @protected
* @static
*/
forceEnum = O._forceEnum = [
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'toLocaleString',
'valueOf'
],
/**
* `true` if this browser has the JScript enumeration bug that prevents
* enumeration of the properties named in the `_forceEnum` array, `false`
* otherwise.
*
* See:
* - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug>
* - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation>
*
* @property _hasEnumBug
* @type Boolean
* @protected
* @static
*/
hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'),
/**
* `true` if this browser incorrectly considers the `prototype` property of
* functions to be enumerable. Currently known to affect Opera 11.50.
*
* @property _hasProtoEnumBug
* @type Boolean
* @protected
* @static
*/
hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'),
/**
* Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or
* exists only on _obj_'s prototype. This is essentially a safer version of
* `obj.hasOwnProperty()`.
*
* @method owns
* @param {Object} obj Object to test.
* @param {String} key Property name to look for.
* @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise.
* @static
*/
owns = O.owns = function (obj, key) {
return !!obj && hasOwn.call(obj, key);
}; // <-- End of var declarations.
/**
* Alias for `owns()`.
*
* @method hasKey
* @param {Object} obj Object to test.
* @param {String} key Property name to look for.
* @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise.
* @static
*/
O.hasKey = owns;
/**
* Returns an array containing the object's enumerable keys. Does not include
* prototype keys or non-enumerable keys.
*
* Note that keys are returned in enumeration order (that is, in the same order
* that they would be enumerated by a `for-in` loop), which may not be the same
* as the order in which they were defined.
*
* This method is an alias for the native ES5 `Object.keys()` method if
* available.
*
* @example
*
* Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'});
* // => ['a', 'b', 'c']
*
* @method keys
* @param {Object} obj An object.
* @return {String[]} Array of keys.
* @static
*/
O.keys = Lang._isNative(Object.keys) ? Object.keys : function (obj) {
if (!Lang.isObject(obj)) {
throw new TypeError('Object.keys called on a non-object');
}
var keys = [],
i, key, len;
if (hasProtoEnumBug && typeof obj === 'function') {
for (key in obj) {
if (owns(obj, key) && key !== 'prototype') {
keys.push(key);
}
}
} else {
for (key in obj) {
if (owns(obj, key)) {
keys.push(key);
}
}
}
if (hasEnumBug) {
for (i = 0, len = forceEnum.length; i < len; ++i) {
key = forceEnum[i];
if (owns(obj, key)) {
keys.push(key);
}
}
}
return keys;
};
/**
* Returns an array containing the values of the object's enumerable keys.
*
* Note that values are returned in enumeration order (that is, in the same
* order that they would be enumerated by a `for-in` loop), which may not be the
* same as the order in which they were defined.
*
* @example
*
* Y.Object.values({a: 'foo', b: 'bar', c: 'baz'});
* // => ['foo', 'bar', 'baz']
*
* @method values
* @param {Object} obj An object.
* @return {Array} Array of values.
* @static
*/
O.values = function (obj) {
var keys = O.keys(obj),
i = 0,
len = keys.length,
values = [];
for (; i < len; ++i) {
values.push(obj[keys[i]]);
}
return values;
};
/**
* Returns the number of enumerable keys owned by an object.
*
* @method size
* @param {Object} obj An object.
* @return {Number} The object's size.
* @static
*/
O.size = function (obj) {
try {
return O.keys(obj).length;
} catch (ex) {
return 0; // Legacy behavior for non-objects.
}
};
/**
* Returns `true` if the object owns an enumerable property with the specified
* value.
*
* @method hasValue
* @param {Object} obj An object.
* @param {any} value The value to search for.
* @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise.
* @static
*/
O.hasValue = function (obj, value) {
return Y.Array.indexOf(O.values(obj), value) > -1;
};
/**
* Executes a function on each enumerable property in _obj_. The function
* receives the value, the key, and the object itself as parameters (in that
* order).
*
* By default, only properties owned by _obj_ are enumerated. To include
* prototype properties, set the _proto_ parameter to `true`.
*
* @method each
* @param {Object} obj Object to enumerate.
* @param {Function} fn Function to execute on each enumerable property.
* @param {mixed} fn.value Value of the current property.
* @param {String} fn.key Key of the current property.
* @param {Object} fn.obj Object being enumerated.
* @param {Object} [thisObj] `this` object to use when calling _fn_.
* @param {Boolean} [proto=false] Include prototype properties.
* @return {YUI} the YUI instance.
* @chainable
* @static
*/
O.each = function (obj, fn, thisObj, proto) {
var key;
for (key in obj) {
if (proto || owns(obj, key)) {
fn.call(thisObj || Y, obj[key], key, obj);
}
}
return Y;
};
/**
* Executes a function on each enumerable property in _obj_, but halts if the
* function returns a truthy value. The function receives the value, the key,
* and the object itself as paramters (in that order).
*
* By default, only properties owned by _obj_ are enumerated. To include
* prototype properties, set the _proto_ parameter to `true`.
*
* @method some
* @param {Object} obj Object to enumerate.
* @param {Function} fn Function to execute on each enumerable property.
* @param {mixed} fn.value Value of the current property.
* @param {String} fn.key Key of the current property.
* @param {Object} fn.obj Object being enumerated.
* @param {Object} [thisObj] `this` object to use when calling _fn_.
* @param {Boolean} [proto=false] Include prototype properties.
* @return {Boolean} `true` if any execution of _fn_ returns a truthy value,
* `false` otherwise.
* @static
*/
O.some = function (obj, fn, thisObj, proto) {
var key;
for (key in obj) {
if (proto || owns(obj, key)) {
if (fn.call(thisObj || Y, obj[key], key, obj)) {
return true;
}
}
}
return false;
};
/**
* Retrieves the sub value at the provided path,
* from the value object provided.
*
* @method getValue
* @static
* @param o The object from which to extract the property value.
* @param path {Array} A path array, specifying the object traversal path
* from which to obtain the sub value.
* @return {Any} The value stored in the path, undefined if not found,
* undefined if the source is not an object. Returns the source object
* if an empty path is provided.
*/
O.getValue = function(o, path) {
if (!Lang.isObject(o)) {
return UNDEFINED;
}
var i,
p = Y.Array(path),
l = p.length;
for (i = 0; o !== UNDEFINED && i < l; i++) {
o = o[p[i]];
}
return o;
};
/**
* Sets the sub-attribute value at the provided path on the
* value object. Returns the modified value object, or
* undefined if the path is invalid.
*
* @method setValue
* @static
* @param o The object on which to set the sub value.
* @param path {Array} A path array, specifying the object traversal path
* at which to set the sub value.
* @param val {Any} The new value for the sub-attribute.
* @return {Object} The modified object, with the new sub value set, or
* undefined, if the path was invalid.
*/
O.setValue = function(o, path, val) {
var i,
p = Y.Array(path),
leafIdx = p.length - 1,
ref = o;
if (leafIdx >= 0) {
for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) {
ref = ref[p[i]];
}
if (ref !== UNDEFINED) {
ref[p[i]] = val;
} else {
return UNDEFINED;
}
}
return o;
};
/**
* Returns `true` if the object has no enumerable properties of its own.
*
* @method isEmpty
* @param {Object} obj An object.
* @return {Boolean} `true` if the object is empty.
* @static
* @since 3.2.0
*/
O.isEmpty = function (obj) {
return !O.keys(Object(obj)).length;
};
/**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and the
* core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* YUI user agent detection.
* Do not fork for a browser if it can be avoided. Use feature detection when
* you can. Use the user agent as a last resort. For all fields listed
* as @type float, UA stores a version number for the browser engine,
* 0 otherwise. This value may or may not map to the version number of
* the browser using the engine. The value is presented as a float so
* that it can easily be used for boolean evaluation as well as for
* looking for a particular range of versions. Because of this,
* some of the granularity of the version info may be lost. The fields that
* are @type string default to null. The API docs list the values that
* these fields can have.
* @class UA
* @static
*/
/**
* Static method on `YUI.Env` for parsing a UA string. Called at instantiation
* to populate `Y.UA`.
*
* @static
* @method parseUA
* @param {String} [subUA=navigator.userAgent] UA string to parse
* @return {Object} The Y.UA object
*/
YUI.Env.parseUA = function(subUA) {
var numberify = function(s) {
var c = 0;
return parseFloat(s.replace(/\./g, function() {
return (c++ == 1) ? '' : '.';
}));
},
win = Y.config.win,
nav = win && win.navigator,
o = {
/**
* Internet Explorer version number or 0. Example: 6
* @property ie
* @type float
* @static
*/
ie: 0,
/**
* Opera version number or 0. Example: 9.2
* @property opera
* @type float
* @static
*/
opera: 0,
/**
* Gecko engine revision number. Will evaluate to 1 if Gecko
* is detected but the revision could not be found. Other browsers
* will be 0. Example: 1.8
* <pre>
* Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7
* Firefox 1.5.0.9: 1.8.0.9 <-- 1.8
* Firefox 2.0.0.3: 1.8.1.3 <-- 1.81
* Firefox 3.0 <-- 1.9
* Firefox 3.5 <-- 1.91
* </pre>
* @property gecko
* @type float
* @static
*/
gecko: 0,
/**
* AppleWebKit version. KHTML browsers that are not WebKit browsers
* will evaluate to 1, other browsers 0. Example: 418.9
* <pre>
* Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the
* latest available for Mac OSX 10.3.
* Safari 2.0.2: 416 <-- hasOwnProperty introduced
* Safari 2.0.4: 418 <-- preventDefault fixed
* Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run
* different versions of webkit
* Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been
* updated, but not updated
* to the latest patch.
* Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native
* SVG and many major issues fixed).
* Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic
* update from 2.x via the 10.4.11 OS patch.
* Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event.
* yahoo.com user agent hack removed.
* </pre>
* http://en.wikipedia.org/wiki/Safari_version_history
* @property webkit
* @type float
* @static
*/
webkit: 0,
/**
* Safari will be detected as webkit, but this property will also
* be populated with the Safari version number
* @property safari
* @type float
* @static
*/
safari: 0,
/**
* Chrome will be detected as webkit, but this property will also
* be populated with the Chrome version number
* @property chrome
* @type float
* @static
*/
chrome: 0,
/**
* The mobile property will be set to a string containing any relevant
* user agent information when a modern mobile browser is detected.
* Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series
* devices with the WebKit-based browser, and Opera Mini.
* @property mobile
* @type string
* @default null
* @static
*/
mobile: null,
/**
* Adobe AIR version number or 0. Only populated if webkit is detected.
* Example: 1.0
* @property air
* @type float
*/
air: 0,
/**
* Detects Apple iPad's OS version
* @property ipad
* @type float
* @static
*/
ipad: 0,
/**
* Detects Apple iPhone's OS version
* @property iphone
* @type float
* @static
*/
iphone: 0,
/**
* Detects Apples iPod's OS version
* @property ipod
* @type float
* @static
*/
ipod: 0,
/**
* General truthy check for iPad, iPhone or iPod
* @property ios
* @type float
* @default null
* @static
*/
ios: null,
/**
* Detects Googles Android OS version
* @property android
* @type float
* @static
*/
android: 0,
/**
* Detects Kindle Silk
* @property silk
* @type float
* @static
*/
silk: 0,
/**
* Detects Kindle Silk Acceleration
* @property accel
* @type Boolean
* @static
*/
accel: false,
/**
* Detects Palms WebOS version
* @property webos
* @type float
* @static
*/
webos: 0,
/**
* Google Caja version number or 0.
* @property caja
* @type float
*/
caja: nav && nav.cajaVersion,
/**
* Set to true if the page appears to be in SSL
* @property secure
* @type boolean
* @static
*/
secure: false,
/**
* The operating system. Currently only detecting windows or macintosh
* @property os
* @type string
* @default null
* @static
*/
os: null,
/**
* The Nodejs Version
* @property nodejs
* @type float
* @default 0
* @static
*/
nodejs: 0
},
ua = subUA || nav && nav.userAgent,
loc = win && win.location,
href = loc && loc.href,
m;
/**
* The User Agent string that was parsed
* @property userAgent
* @type String
* @static
*/
o.userAgent = ua;
o.secure = href && (href.toLowerCase().indexOf('https') === 0);
if (ua) {
if ((/windows|win32/i).test(ua)) {
o.os = 'windows';
} else if ((/macintosh|mac_powerpc/i).test(ua)) {
o.os = 'macintosh';
} else if ((/android/i).test(ua)) {
o.os = 'android';
} else if ((/symbos/i).test(ua)) {
o.os = 'symbos';
} else if ((/linux/i).test(ua)) {
o.os = 'linux';
} else if ((/rhino/i).test(ua)) {
o.os = 'rhino';
}
// Modern KHTML browsers should qualify as Safari X-Grade
if ((/KHTML/).test(ua)) {
o.webkit = 1;
}
if ((/IEMobile|XBLWP7/).test(ua)) {
o.mobile = 'windows';
}
if ((/Fennec/).test(ua)) {
o.mobile = 'gecko';
}
// Modern WebKit browsers are at least X-Grade
m = ua.match(/AppleWebKit\/([^\s]*)/);
if (m && m[1]) {
o.webkit = numberify(m[1]);
o.safari = o.webkit;
// Mobile browser check
if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) {
o.mobile = 'Apple'; // iPhone or iPod Touch
m = ua.match(/OS ([^\s]*)/);
if (m && m[1]) {
m = numberify(m[1].replace('_', '.'));
}
o.ios = m;
o.os = 'ios';
o.ipad = o.ipod = o.iphone = 0;
m = ua.match(/iPad|iPod|iPhone/);
if (m && m[0]) {
o[m[0].toLowerCase()] = o.ios;
}
} else {
m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/);
if (m) {
// Nokia N-series, webOS, ex: NokiaN95
o.mobile = m[0];
}
if (/webOS/.test(ua)) {
o.mobile = 'WebOS';
m = ua.match(/webOS\/([^\s]*);/);
if (m && m[1]) {
o.webos = numberify(m[1]);
}
}
if (/ Android/.test(ua)) {
if (/Mobile/.test(ua)) {
o.mobile = 'Android';
}
m = ua.match(/Android ([^\s]*);/);
if (m && m[1]) {
o.android = numberify(m[1]);
}
}
if (/Silk/.test(ua)) {
m = ua.match(/Silk\/([^\s]*)\)/);
if (m && m[1]) {
o.silk = numberify(m[1]);
}
if (!o.android) {
o.android = 2.34; //Hack for desktop mode in Kindle
o.os = 'Android';
}
if (/Accelerated=true/.test(ua)) {
o.accel = true;
}
}
}
m = ua.match(/(Chrome|CrMo)\/([^\s]*)/);
if (m && m[1] && m[2]) {
o.chrome = numberify(m[2]); // Chrome
o.safari = 0; //Reset safari back to 0
if (m[1] === 'CrMo') {
o.mobile = 'chrome';
}
} else {
m = ua.match(/AdobeAIR\/([^\s]*)/);
if (m) {
o.air = m[0]; // Adobe AIR 1.0 or better
}
}
}
if (!o.webkit) { // not webkit
// @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
if (/Opera/.test(ua)) {
m = ua.match(/Opera[\s\/]([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]);
}
m = ua.match(/Version\/([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]); // opera 10+
}
if (/Opera Mobi/.test(ua)) {
o.mobile = 'opera';
m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]);
}
}
m = ua.match(/Opera Mini[^;]*/);
if (m) {
o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
}
} else { // not opera or webkit
m = ua.match(/MSIE\s([^;]*)/);
if (m && m[1]) {
o.ie = numberify(m[1]);
} else { // not opera, webkit, or ie
m = ua.match(/Gecko\/([^\s]*)/);
if (m) {
o.gecko = 1; // Gecko detected, look for revision
m = ua.match(/rv:([^\s\)]*)/);
if (m && m[1]) {
o.gecko = numberify(m[1]);
}
}
}
}
}
}
//It was a parsed UA, do not assign the global value.
if (!subUA) {
if (typeof process == 'object') {
if (process.versions && process.versions.node) {
//NodeJS
o.os = process.platform;
o.nodejs = process.versions.node;
}
}
YUI.Env.UA = o;
}
return o;
};
Y.UA = YUI.Env.UA || YUI.Env.parseUA();
YUI.Env.aliases = {
"anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"],
"app": ["app-base","app-transitions","model","model-list","router","view"],
"attribute": ["attribute-base","attribute-complex"],
"autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"],
"base": ["base-base","base-pluginhost","base-build"],
"cache": ["cache-base","cache-offline","cache-plugin"],
"collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"],
"controller": ["router"],
"dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"],
"datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"],
"datatable": ["datatable-core","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"],
"datatable-deprecated": ["datatable-base-deprecated","datatable-datasource-deprecated","datatable-sort-deprecated","datatable-scroll-deprecated"],
"datatype": ["datatype-number","datatype-date","datatype-xml"],
"datatype-date": ["datatype-date-parse","datatype-date-format"],
"datatype-number": ["datatype-number-parse","datatype-number-format"],
"datatype-xml": ["datatype-xml-parse","datatype-xml-format"],
"dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"],
"dom": ["dom-base","dom-screen","dom-style","selector-native","selector"],
"editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"],
"event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange"],
"event-custom": ["event-custom-base","event-custom-complex"],
"event-gestures": ["event-flick","event-move"],
"handlebars": ["handlebars-compiler"],
"highlight": ["highlight-base","highlight-accentfold"],
"history": ["history-base","history-hash","history-hash-ie","history-html5"],
"io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"],
"json": ["json-parse","json-stringify"],
"loader": ["loader-base","loader-rollup","loader-yui3"],
"node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"],
"pluginhost": ["pluginhost-base","pluginhost-config"],
"querystring": ["querystring-parse","querystring-stringify"],
"recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"],
"resize": ["resize-base","resize-proxy","resize-constrain"],
"slider": ["slider-base","slider-value-range","clickable-rail","range-slider"],
"text": ["text-accentfold","text-wordbreak"],
"widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"]
};
}, '@VERSION@' );
YUI.add('get', function(Y) {
/*jslint boss:true, expr:true, laxbreak: true */
/**
Provides dynamic loading of remote JavaScript and CSS resources.
@module get
@class Get
@static
**/
var Lang = Y.Lang,
CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode()
Get, Transaction;
Y.Get = Get = {
// -- Public Properties ----------------------------------------------------
/**
Default options for CSS requests. Options specified here will override
global defaults for CSS requests.
See the `options` property for all available options.
@property cssOptions
@type Object
@static
@since 3.5.0
**/
cssOptions: {
attributes: {
rel: 'stylesheet'
},
doc : Y.config.linkDoc || Y.config.doc,
pollInterval: 50
},
/**
Default options for JS requests. Options specified here will override global
defaults for JS requests.
See the `options` property for all available options.
@property jsOptions
@type Object
@static
@since 3.5.0
**/
jsOptions: {
autopurge: true,
doc : Y.config.scriptDoc || Y.config.doc
},
/**
Default options to use for all requests.
Note that while all available options are documented here for ease of
discovery, some options (like callback functions) only make sense at the
transaction level.
Callback functions specified via the options object or the `options`
parameter of the `css()`, `js()`, or `load()` methods will receive the
transaction object as a parameter. See `Y.Get.Transaction` for details on
the properties and methods available on transactions.
@static
@since 3.5.0
@property {Object} options
@property {Boolean} [options.async=false] Whether or not to load scripts
asynchronously, meaning they're requested in parallel and execution
order is not guaranteed. Has no effect on CSS, since CSS is always
loaded asynchronously.
@property {Object} [options.attributes] HTML attribute name/value pairs that
should be added to inserted nodes. By default, the `charset` attribute
will be set to "utf-8" and nodes will be given an auto-generated `id`
attribute, but you can override these with your own values if desired.
@property {Boolean} [options.autopurge] Whether or not to automatically
purge inserted nodes after the purge threshold is reached. This is
`true` by default for JavaScript, but `false` for CSS since purging a
CSS node will also remove any styling applied by the referenced file.
@property {Object} [options.context] `this` object to use when calling
callback functions. Defaults to the transaction object.
@property {Mixed} [options.data] Arbitrary data object to pass to "on*"
callbacks.
@property {Document} [options.doc] Document into which nodes should be
inserted. By default, the current document is used.
@property {HTMLElement|String} [options.insertBefore] HTML element or id
string of an element before which all generated nodes should be
inserted. If not specified, Get will automatically determine the best
place to insert nodes for maximum compatibility.
@property {Function} [options.onEnd] Callback to execute after a transaction
is complete, regardless of whether it succeeded or failed.
@property {Function} [options.onFailure] Callback to execute after a
transaction fails, times out, or is aborted.
@property {Function} [options.onProgress] Callback to execute after each
individual request in a transaction either succeeds or fails.
@property {Function} [options.onSuccess] Callback to execute after a
transaction completes successfully with no errors. Note that in browsers
that don't support the `error` event on CSS `<link>` nodes, a failed CSS
request may still be reported as a success because in these browsers
it can be difficult or impossible to distinguish between success and
failure for CSS resources.
@property {Function} [options.onTimeout] Callback to execute after a
transaction times out.
@property {Number} [options.pollInterval=50] Polling interval (in
milliseconds) for detecting CSS load completion in browsers that don't
support the `load` event on `<link>` nodes. This isn't used for
JavaScript.
@property {Number} [options.purgethreshold=20] Number of nodes to insert
before triggering an automatic purge when `autopurge` is `true`.
@property {Number} [options.timeout] Number of milliseconds to wait before
aborting a transaction. When a timeout occurs, the `onTimeout` callback
is called, followed by `onFailure` and finally `onEnd`. By default,
there is no timeout.
@property {String} [options.type] Resource type ("css" or "js"). This option
is set automatically by the `css()` and `js()` functions and will be
ignored there, but may be useful when using the `load()` function. If
not specified, the type will be inferred from the URL, defaulting to
"js" if the URL doesn't contain a recognizable file extension.
**/
options: {
attributes: {
charset: 'utf-8'
},
purgethreshold: 20
},
// -- Protected Properties -------------------------------------------------
/**
Regex that matches a CSS URL. Used to guess the file type when it's not
specified.
@property REGEX_CSS
@type RegExp
@final
@protected
@static
@since 3.5.0
**/
REGEX_CSS: /\.css(?:[?;].*)?$/i,
/**
Regex that matches a JS URL. Used to guess the file type when it's not
specified.
@property REGEX_JS
@type RegExp
@final
@protected
@static
@since 3.5.0
**/
REGEX_JS : /\.js(?:[?;].*)?$/i,
/**
Contains information about the current environment, such as what script and
link injection features it supports.
This object is created and populated the first time the `_getEnv()` method
is called.
@property _env
@type Object
@protected
@static
@since 3.5.0
**/
/**
Mapping of document _yuid strings to <head> or <base> node references so we
don't have to look the node up each time we want to insert a request node.
@property _insertCache
@type Object
@protected
@static
@since 3.5.0
**/
_insertCache: {},
/**
Information about the currently pending transaction, if any.
This is actually an object with two properties: `callback`, containing the
optional callback passed to `css()`, `load()`, or `js()`; and `transaction`,
containing the actual transaction instance.
@property _pending
@type Object
@protected
@static
@since 3.5.0
**/
_pending: null,
/**
HTML nodes eligible to be purged next time autopurge is triggered.
@property _purgeNodes
@type HTMLElement[]
@protected
@static
@since 3.5.0
**/
_purgeNodes: [],
/**
Queued transactions and associated callbacks.
@property _queue
@type Object[]
@protected
@static
@since 3.5.0
**/
_queue: [],
// -- Public Methods -------------------------------------------------------
/**
Aborts the specified transaction.
This will cause the transaction's `onFailure` callback to be called and
will prevent any new script and link nodes from being added to the document,
but any resources that have already been requested will continue loading
(there's no safe way to prevent this, unfortunately).
*Note:* This method is deprecated as of 3.5.0, and will be removed in a
future version of YUI. Use the transaction-level `abort()` method instead.
@method abort
@param {Get.Transaction} transaction Transaction to abort.
@deprecated Use the `abort()` method on the transaction instead.
@static
**/
abort: function (transaction) {
var i, id, item, len, pending;
Y.log('`Y.Get.abort()` is deprecated as of 3.5.0. Use the `abort()` method on the transaction instead.', 'warn', 'get');
if (!transaction.abort) {
id = transaction;
pending = this._pending;
transaction = null;
if (pending && pending.transaction.id === id) {
transaction = pending.transaction;
this._pending = null;
} else {
for (i = 0, len = this._queue.length; i < len; ++i) {
item = this._queue[i].transaction;
if (item.id === id) {
transaction = item;
this._queue.splice(i, 1);
break;
}
}
}
}
transaction && transaction.abort();
},
/**
Loads one or more CSS files.
The _urls_ parameter may be provided as a URL string, a request object,
or an array of URL strings and/or request objects.
A request object is just an object that contains a `url` property and zero
or more options that should apply specifically to that request.
Request-specific options take priority over transaction-level options and
default options.
URLs may be relative or absolute, and do not have to have the same origin
as the current page.
The `options` parameter may be omitted completely and a callback passed in
its place, if desired.
@example
// Load a single CSS file and log a message on completion.
Y.Get.css('foo.css', function (err) {
if (err) {
Y.log('foo.css failed to load!');
} else {
Y.log('foo.css was loaded successfully');
}
});
// Load multiple CSS files and log a message when all have finished
// loading.
var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css'];
Y.Get.css(urls, function (err) {
if (err) {
Y.log('one or more files failed to load!');
} else {
Y.log('all files loaded successfully');
}
});
// Specify transaction-level options, which will apply to all requests
// within the transaction.
Y.Get.css(urls, {
attributes: {'class': 'my-css'},
timeout : 5000
});
// Specify per-request options, which override transaction-level and
// default options.
Y.Get.css([
{url: 'foo.css', attributes: {id: 'foo'}},
{url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}}
]);
@method css
@param {String|Object|Array} urls URL string, request object, or array
of URLs and/or request objects to load.
@param {Object} [options] Options for this transaction. See the
`Y.Get.options` property for a complete list of available options.
@param {Function} [callback] Callback function to be called on completion.
This is a general callback and will be called before any more granular
callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options`
object.
@param {Array|null} callback.err Array of errors that occurred during
the transaction, or `null` on success.
@param {Get.Transaction} callback.transaction Transaction object.
@return {Get.Transaction} Transaction object.
@static
**/
css: function (urls, options, callback) {
return this._load('css', urls, options, callback);
},
/**
Loads one or more JavaScript resources.
The _urls_ parameter may be provided as a URL string, a request object,
or an array of URL strings and/or request objects.
A request object is just an object that contains a `url` property and zero
or more options that should apply specifically to that request.
Request-specific options take priority over transaction-level options and
default options.
URLs may be relative or absolute, and do not have to have the same origin
as the current page.
The `options` parameter may be omitted completely and a callback passed in
its place, if desired.
Scripts will be executed in the order they're specified unless the `async`
option is `true`, in which case they'll be loaded in parallel and executed
in whatever order they finish loading.
@example
// Load a single JS file and log a message on completion.
Y.Get.js('foo.js', function (err) {
if (err) {
Y.log('foo.js failed to load!');
} else {
Y.log('foo.js was loaded successfully');
}
});
// Load multiple JS files, execute them in order, and log a message when
// all have finished loading.
var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js'];
Y.Get.js(urls, function (err) {
if (err) {
Y.log('one or more files failed to load!');
} else {
Y.log('all files loaded successfully');
}
});
// Specify transaction-level options, which will apply to all requests
// within the transaction.
Y.Get.js(urls, {
attributes: {'class': 'my-js'},
timeout : 5000
});
// Specify per-request options, which override transaction-level and
// default options.
Y.Get.js([
{url: 'foo.js', attributes: {id: 'foo'}},
{url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}}
]);
@method js
@param {String|Object|Array} urls URL string, request object, or array
of URLs and/or request objects to load.
@param {Object} [options] Options for this transaction. See the
`Y.Get.options` property for a complete list of available options.
@param {Function} [callback] Callback function to be called on completion.
This is a general callback and will be called before any more granular
callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options`
object.
@param {Array|null} callback.err Array of errors that occurred during
the transaction, or `null` on success.
@param {Get.Transaction} callback.transaction Transaction object.
@return {Get.Transaction} Transaction object.
@since 3.5.0
@static
**/
js: function (urls, options, callback) {
return this._load('js', urls, options, callback);
},
/**
Loads one or more CSS and/or JavaScript resources in the same transaction.
Use this method when you want to load both CSS and JavaScript in a single
transaction and be notified when all requested URLs have finished loading,
regardless of type.
Behavior and options are the same as for the `css()` and `js()` methods. If
a resource type isn't specified in per-request options or transaction-level
options, Get will guess the file type based on the URL's extension (`.css`
or `.js`, with or without a following query string). If the file type can't
be guessed from the URL, a warning will be logged and Get will assume the
URL is a JavaScript resource.
@example
// Load both CSS and JS files in a single transaction, and log a message
// when all files have finished loading.
Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) {
if (err) {
Y.log('one or more files failed to load!');
} else {
Y.log('all files loaded successfully');
}
});
@method load
@param {String|Object|Array} urls URL string, request object, or array
of URLs and/or request objects to load.
@param {Object} [options] Options for this transaction. See the
`Y.Get.options` property for a complete list of available options.
@param {Function} [callback] Callback function to be called on completion.
This is a general callback and will be called before any more granular
callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options`
object.
@param {Array|null} err Array of errors that occurred during the
transaction, or `null` on success.
@param {Get.Transaction} Transaction object.
@return {Get.Transaction} Transaction object.
@since 3.5.0
@static
**/
load: function (urls, options, callback) {
return this._load(null, urls, options, callback);
},
// -- Protected Methods ----------------------------------------------------
/**
Triggers an automatic purge if the purge threshold has been reached.
@method _autoPurge
@param {Number} threshold Purge threshold to use, in milliseconds.
@protected
@since 3.5.0
@static
**/
_autoPurge: function (threshold) {
if (threshold && this._purgeNodes.length >= threshold) {
Y.log('autopurge triggered after ' + this._purgeNodes.length + ' nodes', 'info', 'get');
this._purge(this._purgeNodes);
}
},
/**
Populates the `_env` property with information about the current
environment.
@method _getEnv
@return {Object} Environment information.
@protected
@since 3.5.0
@static
**/
_getEnv: function () {
var doc = Y.config.doc,
ua = Y.UA;
// Note: some of these checks require browser sniffs since it's not
// feasible to load test files on every pageview just to perform a
// feature test. I'm sorry if this makes you sad.
return (this._env = {
// True if this is a browser that supports disabling async mode on
// dynamically created script nodes. See
// https://developer.mozilla.org/En/HTML/Element/Script#Attributes
async: doc && doc.createElement('script').async === true,
// True if this browser fires an event when a dynamically injected
// link node fails to load. This is currently true for Firefox 9+
// and WebKit 535.24+.
cssFail: ua.gecko >= 9 || ua.webkit >= 535.24,
// True if this browser fires an event when a dynamically injected
// link node finishes loading. This is currently true for IE, Opera,
// Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the
// DOM 0 "onload" event, but not "load". All versions of IE fire
// "onload".
// davglass: Seems that Chrome on Android needs this to be false.
cssLoad: ((!ua.gecko && !ua.webkit) ||
ua.gecko >= 9 || ua.webkit >= 535.24) && !(ua.chrome && ua.chrome <=18),
// True if this browser preserves script execution order while
// loading scripts in parallel as long as the script node's `async`
// attribute is set to false to explicitly disable async execution.
preservesScriptOrder: !!(ua.gecko || ua.opera)
});
},
_getTransaction: function (urls, options) {
var requests = [],
i, len, req, url;
if (!Lang.isArray(urls)) {
urls = [urls];
}
options = Y.merge(this.options, options);
// Clone the attributes object so we don't end up modifying it by ref.
options.attributes = Y.merge(this.options.attributes,
options.attributes);
for (i = 0, len = urls.length; i < len; ++i) {
url = urls[i];
req = {attributes: {}};
// If `url` is a string, we create a URL object for it, then mix in
// global options and request-specific options. If it's an object
// with a "url" property, we assume it's a request object containing
// URL-specific options.
if (typeof url === 'string') {
req.url = url;
} else if (url.url) {
// URL-specific options override both global defaults and
// request-specific options.
Y.mix(req, url, false, null, 0, true);
url = url.url; // Make url a string so we can use it later.
} else {
Y.log('URL must be a string or an object with a `url` property.', 'error', 'get');
continue;
}
Y.mix(req, options, false, null, 0, true);
// If we didn't get an explicit type for this URL either in the
// request options or the URL-specific options, try to determine
// one from the file extension.
if (!req.type) {
if (this.REGEX_CSS.test(url)) {
req.type = 'css';
} else {
if (!this.REGEX_JS.test(url)) {
Y.log("Can't guess file type from URL. Assuming JS: " + url, 'warn', 'get');
}
req.type = 'js';
}
}
// Mix in type-specific default options, but don't overwrite any
// options that have already been set.
Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions,
false, null, 0, true);
// Give the node an id attribute if it doesn't already have one.
req.attributes.id || (req.attributes.id = Y.guid());
// Backcompat for <3.5.0 behavior.
if (req.win) {
Y.log('The `win` option is deprecated as of 3.5.0. Use `doc` instead.', 'warn', 'get');
req.doc = req.win.document;
} else {
req.win = req.doc.defaultView || req.doc.parentWindow;
}
if (req.charset) {
Y.log('The `charset` option is deprecated as of 3.5.0. Set `attributes.charset` instead.', 'warn', 'get');
req.attributes.charset = req.charset;
}
requests.push(req);
}
return new Transaction(requests, options);
},
_load: function (type, urls, options, callback) {
var transaction;
// Allow callback as third param.
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
options.type = type;
if (!this._env) {
this._getEnv();
}
transaction = this._getTransaction(urls, options);
this._queue.push({
callback : callback,
transaction: transaction
});
this._next();
return transaction;
},
_next: function () {
var item;
if (this._pending) {
return;
}
item = this._queue.shift();
if (item) {
this._pending = item;
item.transaction.execute(function () {
item.callback && item.callback.apply(this, arguments);
Get._pending = null;
Get._next();
});
}
},
_purge: function (nodes) {
var purgeNodes = this._purgeNodes,
isTransaction = nodes !== purgeNodes,
index, node;
while (node = nodes.pop()) { // assignment
// Don't purge nodes that haven't finished loading (or errored out),
// since this can hang the transaction.
if (!node._yuiget_finished) {
continue;
}
node.parentNode && node.parentNode.removeChild(node);
// If this is a transaction-level purge and this node also exists in
// the Get-level _purgeNodes array, we need to remove it from
// _purgeNodes to avoid creating a memory leak. The indexOf lookup
// sucks, but until we get WeakMaps, this is the least troublesome
// way to do this (we can't just hold onto node ids because they may
// not be in the same document).
if (isTransaction) {
index = Y.Array.indexOf(purgeNodes, node);
if (index > -1) {
purgeNodes.splice(index, 1);
}
}
}
}
};
/**
Alias for `js()`.
@method script
@static
**/
Get.script = Get.js;
/**
Represents a Get transaction, which may contain requests for one or more JS or
CSS files.
This class should not be instantiated manually. Instances will be created and
returned as needed by Y.Get's `css()`, `js()`, and `load()` methods.
@class Get.Transaction
@constructor
@since 3.5.0
**/
Get.Transaction = Transaction = function (requests, options) {
var self = this;
self.id = Transaction._lastId += 1;
self.data = options.data;
self.errors = [];
self.nodes = [];
self.options = options;
self.requests = requests;
self._callbacks = []; // callbacks to call after execution finishes
self._queue = [];
self._waiting = 0;
// Deprecated pre-3.5.0 properties.
self.tId = self.id; // Use `id` instead.
self.win = options.win || Y.config.win;
};
/**
Arbitrary data object associated with this transaction.
This object comes from the options passed to `Get.css()`, `Get.js()`, or
`Get.load()`, and will be `undefined` if no data object was specified.
@property {Object} data
**/
/**
Array of errors that have occurred during this transaction, if any.
@since 3.5.0
@property {Object[]} errors
@property {String} errors.error Error message.
@property {Object} errors.request Request object related to the error.
**/
/**
Numeric id for this transaction, unique among all transactions within the same
YUI sandbox in the current pageview.
@property {Number} id
@since 3.5.0
**/
/**
HTMLElement nodes (native ones, not YUI Node instances) that have been inserted
during the current transaction.
@property {HTMLElement[]} nodes
**/
/**
Options associated with this transaction.
See `Get.options` for the full list of available options.
@property {Object} options
@since 3.5.0
**/
/**
Request objects contained in this transaction. Each request object represents
one CSS or JS URL that will be (or has been) requested and loaded into the page.
@property {Object} requests
@since 3.5.0
**/
/**
Id of the most recent transaction.
@property _lastId
@type Number
@protected
@static
**/
Transaction._lastId = 0;
Transaction.prototype = {
// -- Public Properties ----------------------------------------------------
/**
Current state of this transaction. One of "new", "executing", or "done".
@property _state
@type String
@protected
**/
_state: 'new', // "new", "executing", or "done"
// -- Public Methods -------------------------------------------------------
/**
Aborts this transaction.
This will cause the transaction's `onFailure` callback to be called and
will prevent any new script and link nodes from being added to the document,
but any resources that have already been requested will continue loading
(there's no safe way to prevent this, unfortunately).
@method abort
@param {String} [msg="Aborted."] Optional message to use in the `errors`
array describing why the transaction was aborted.
**/
abort: function (msg) {
this._pending = null;
this._pendingCSS = null;
this._pollTimer = clearTimeout(this._pollTimer);
this._queue = [];
this._waiting = 0;
this.errors.push({error: msg || 'Aborted'});
this._finish();
},
/**
Begins execting the transaction.
There's usually no reason to call this manually, since Get will call it
automatically when other pending transactions have finished. If you really
want to execute your transaction before Get does, you can, but be aware that
this transaction's scripts may end up executing before the scripts in other
pending transactions.
If the transaction is already executing, the specified callback (if any)
will be queued and called after execution finishes. If the transaction has
already finished, the callback will be called immediately (the transaction
will not be executed again).
@method execute
@param {Function} callback Callback function to execute after all requests
in the transaction are complete, or after the transaction is aborted.
**/
execute: function (callback) {
var self = this,
requests = self.requests,
state = self._state,
i, len, queue, req;
if (state === 'done') {
callback && callback(self.errors.length ? self.errors : null, self);
return;
} else {
callback && self._callbacks.push(callback);
if (state === 'executing') {
return;
}
}
self._state = 'executing';
self._queue = queue = [];
if (self.options.timeout) {
self._timeout = setTimeout(function () {
self.abort('Timeout');
}, self.options.timeout);
}
for (i = 0, len = requests.length; i < len; ++i) {
req = self.requests[i];
if (req.async || req.type === 'css') {
// No need to queue CSS or fully async JS.
self._insert(req);
} else {
queue.push(req);
}
}
self._next();
},
/**
Manually purges any `<script>` or `<link>` nodes this transaction has
created.
Be careful when purging a transaction that contains CSS requests, since
removing `<link>` nodes will also remove any styles they applied.
@method purge
**/
purge: function () {
Get._purge(this.nodes);
},
// -- Protected Methods ----------------------------------------------------
_createNode: function (name, attrs, doc) {
var node = doc.createElement(name),
attr, testEl;
if (!CUSTOM_ATTRS) {
// IE6 and IE7 expect property names rather than attribute names for
// certain attributes. Rather than sniffing, we do a quick feature
// test the first time _createNode() runs to determine whether we
// need to provide a workaround.
testEl = doc.createElement('div');
testEl.setAttribute('class', 'a');
CUSTOM_ATTRS = testEl.className === 'a' ? {} : {
'for' : 'htmlFor',
'class': 'className'
};
}
for (attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]);
}
}
return node;
},
_finish: function () {
var errors = this.errors.length ? this.errors : null,
options = this.options,
thisObj = options.context || this,
data, i, len;
if (this._state === 'done') {
return;
}
this._state = 'done';
for (i = 0, len = this._callbacks.length; i < len; ++i) {
this._callbacks[i].call(thisObj, errors, this);
}
data = this._getEventData();
if (errors) {
if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') {
options.onTimeout.call(thisObj, data);
}
if (options.onFailure) {
options.onFailure.call(thisObj, data);
}
} else if (options.onSuccess) {
options.onSuccess.call(thisObj, data);
}
if (options.onEnd) {
options.onEnd.call(thisObj, data);
}
},
_getEventData: function (req) {
if (req) {
// This merge is necessary for backcompat. I hate it.
return Y.merge(this, {
abort : this.abort, // have to copy these because the prototype isn't preserved
purge : this.purge,
request: req,
url : req.url,
win : req.win
});
} else {
return this;
}
},
_getInsertBefore: function (req) {
var doc = req.doc,
el = req.insertBefore,
cache, cachedNode, docStamp;
if (el) {
return typeof el === 'string' ? doc.getElementById(el) : el;
}
cache = Get._insertCache;
docStamp = Y.stamp(doc);
if ((el = cache[docStamp])) { // assignment
return el;
}
// Inserting before a <base> tag apparently works around an IE bug
// (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what
// bug that is, exactly. Better safe than sorry?
if ((el = doc.getElementsByTagName('base')[0])) { // assignment
return (cache[docStamp] = el);
}
// Look for a <head> element.
el = doc.head || doc.getElementsByTagName('head')[0];
if (el) {
// Create a marker node at the end of <head> to use as an insertion
// point. Inserting before this node will ensure that all our CSS
// gets inserted in the correct order, to maintain style precedence.
el.appendChild(doc.createTextNode(''));
return (cache[docStamp] = el.lastChild);
}
// If all else fails, just insert before the first script node on the
// page, which is virtually guaranteed to exist.
return (cache[docStamp] = doc.getElementsByTagName('script')[0]);
},
_insert: function (req) {
var env = Get._env,
insertBefore = this._getInsertBefore(req),
isScript = req.type === 'js',
node = req.node,
self = this,
ua = Y.UA,
cssTimeout, nodeType;
if (!node) {
if (isScript) {
nodeType = 'script';
} else if (!env.cssLoad && ua.gecko) {
nodeType = 'style';
} else {
nodeType = 'link';
}
node = req.node = this._createNode(nodeType, req.attributes,
req.doc);
}
function onError() {
self._progress('Failed to load ' + req.url, req);
}
function onLoad() {
if (cssTimeout) {
clearTimeout(cssTimeout);
}
self._progress(null, req);
}
// Deal with script asynchronicity.
if (isScript) {
node.setAttribute('src', req.url);
if (req.async) {
// Explicitly indicate that we want the browser to execute this
// script asynchronously. This is necessary for older browsers
// like Firefox <4.
node.async = true;
} else {
if (env.async) {
// This browser treats injected scripts as async by default
// (standard HTML5 behavior) but asynchronous loading isn't
// desired, so tell the browser not to mark this script as
// async.
node.async = false;
}
// If this browser doesn't preserve script execution order based
// on insertion order, we'll need to avoid inserting other
// scripts until this one finishes loading.
if (!env.preservesScriptOrder) {
this._pending = req;
}
}
} else {
if (!env.cssLoad && ua.gecko) {
// In Firefox <9, we can import the requested URL into a <style>
// node and poll for the existence of node.sheet.cssRules. This
// gives us a reliable way to determine CSS load completion that
// also works for cross-domain stylesheets.
//
// Props to Zach Leatherman for calling my attention to this
// technique.
node.innerHTML = (req.attributes.charset ?
'@charset "' + req.attributes.charset + '";' : '') +
'@import "' + req.url + '";';
} else {
node.setAttribute('href', req.url);
}
}
// Inject the node.
if (isScript && ua.ie && ua.ie < 9) {
// Script on IE6, 7, and 8.
node.onreadystatechange = function () {
if (/loaded|complete/.test(node.readyState)) {
node.onreadystatechange = null;
onLoad();
}
};
} else if (!isScript && !env.cssLoad) {
// CSS on Firefox <9 or WebKit.
this._poll(req);
} else {
// Script or CSS on everything else. Using DOM 0 events because that
// evens the playing field with older IEs.
node.onerror = onError;
node.onload = onLoad;
// If this browser doesn't fire an event when CSS fails to load,
// fail after a timeout to avoid blocking the transaction queue.
if (!env.cssFail && !isScript) {
cssTimeout = setTimeout(onError, req.timeout || 3000);
}
}
this._waiting += 1;
this.nodes.push(node);
insertBefore.parentNode.insertBefore(node, insertBefore);
},
_next: function () {
if (this._pending) {
return;
}
// If there are requests in the queue, insert the next queued request.
// Otherwise, if we're waiting on already-inserted requests to finish,
// wait longer. If there are no queued requests and we're not waiting
// for anything to load, then we're done!
if (this._queue.length) {
this._insert(this._queue.shift());
} else if (!this._waiting) {
this._finish();
}
},
_poll: function (newReq) {
var self = this,
pendingCSS = self._pendingCSS,
isWebKit = Y.UA.webkit,
i, hasRules, j, nodeHref, req, sheets;
if (newReq) {
pendingCSS || (pendingCSS = self._pendingCSS = []);
pendingCSS.push(newReq);
if (self._pollTimer) {
// A poll timeout is already pending, so no need to create a
// new one.
return;
}
}
self._pollTimer = null;
// Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s
// will still be treated as a success. There's no good workaround for
// this.
for (i = 0; i < pendingCSS.length; ++i) {
req = pendingCSS[i];
if (isWebKit) {
// Look for a stylesheet matching the pending URL.
sheets = req.doc.styleSheets;
j = sheets.length;
nodeHref = req.node.href;
while (--j >= 0) {
if (sheets[j].href === nodeHref) {
pendingCSS.splice(i, 1);
i -= 1;
self._progress(null, req);
break;
}
}
} else {
// Many thanks to Zach Leatherman for calling my attention to
// the @import-based cross-domain technique used here, and to
// Oleg Slobodskoi for an earlier same-domain implementation.
//
// See Zach's blog for more details:
// http://www.zachleat.com/web/2010/07/29/load-css-dynamically/
try {
// We don't really need to store this value since we never
// use it again, but if we don't store it, Closure Compiler
// assumes the code is useless and removes it.
hasRules = !!req.node.sheet.cssRules;
// If we get here, the stylesheet has loaded.
pendingCSS.splice(i, 1);
i -= 1;
self._progress(null, req);
} catch (ex) {
// An exception means the stylesheet is still loading.
}
}
}
if (pendingCSS.length) {
self._pollTimer = setTimeout(function () {
self._poll.call(self);
}, self.options.pollInterval);
}
},
_progress: function (err, req) {
var options = this.options;
if (err) {
req.error = err;
this.errors.push({
error : err,
request: req
});
Y.log(err, 'error', 'get');
}
req.node._yuiget_finished = req.finished = true;
if (options.onProgress) {
options.onProgress.call(options.context || this,
this._getEventData(req));
}
if (req.autopurge) {
// Pre-3.5.0 Get always excludes the most recent node from an
// autopurge. I find this odd, but I'm keeping that behavior for
// the sake of backcompat.
Get._autoPurge(this.options.purgethreshold);
Get._purgeNodes.push(req.node);
}
if (this._pending === req) {
this._pending = null;
}
this._waiting -= 1;
this._next();
}
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('features', function(Y) {
var feature_tests = {};
/**
Contains the core of YUI's feature test architecture.
@module features
*/
/**
* Feature detection
* @class Features
* @static
*/
Y.mix(Y.namespace('Features'), {
/**
* Object hash of all registered feature tests
* @property tests
* @type Object
*/
tests: feature_tests,
/**
* Add a test to the system
*
* ```
* Y.Features.add("load", "1", {});
* ```
*
* @method add
* @param {String} cat The category, right now only 'load' is supported
* @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3
* @param {Object} o Object containing test properties
* @param {String} o.name The name of the test
* @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance
* @param {String} o.trigger The module that triggers this test.
*/
add: function(cat, name, o) {
feature_tests[cat] = feature_tests[cat] || {};
feature_tests[cat][name] = o;
},
/**
* Execute all tests of a given category and return the serialized results
*
* ```
* caps=1:1;2:1;3:0
* ```
* @method all
* @param {String} cat The category to execute
* @param {Array} args The arguments to pass to the test function
* @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0
*/
all: function(cat, args) {
var cat_o = feature_tests[cat],
// results = {};
result = [];
if (cat_o) {
Y.Object.each(cat_o, function(v, k) {
result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0));
});
}
return (result.length) ? result.join(';') : '';
},
/**
* Run a sepecific test and return a Boolean response.
*
* ```
* Y.Features.test("load", "1");
* ```
*
* @method test
* @param {String} cat The category of the test to run
* @param {String} name The name of the test to run
* @param {Array} args The arguments to pass to the test function
* @return {Boolean} True or false if the test passed/failed.
*/
test: function(cat, name, args) {
args = args || [];
var result, ua, test,
cat_o = feature_tests[cat],
feature = cat_o && cat_o[name];
if (!feature) {
Y.log('Feature test ' + cat + ', ' + name + ' not found');
} else {
result = feature.result;
if (Y.Lang.isUndefined(result)) {
ua = feature.ua;
if (ua) {
result = (Y.UA[ua]);
}
test = feature.test;
if (test && ((!ua) || result)) {
result = test.apply(Y, args);
}
feature.result = result;
}
}
return result;
}
});
// Y.Features.add("load", "1", {});
// Y.Features.test("load", "1");
// caps=1:1;2:0;3:1;
/* This file is auto-generated by src/loader/scripts/meta_join.py */
var add = Y.Features.add;
// io-nodejs
add('load', '0', {
"name": "io-nodejs",
"trigger": "io-base",
"ua": "nodejs"
});
// graphics-canvas-default
add('load', '1', {
"name": "graphics-canvas-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d"));
},
"trigger": "graphics"
});
// autocomplete-list-keys
add('load', '2', {
"name": "autocomplete-list-keys",
"test": function (Y) {
// Only add keyboard support to autocomplete-list if this doesn't appear to
// be an iOS or Android-based mobile device.
//
// There's currently no feasible way to actually detect whether a device has
// a hardware keyboard, so this sniff will have to do. It can easily be
// overridden by manually loading the autocomplete-list-keys module.
//
// Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari
// doesn't fire the keyboard events used by AutoCompleteList, so there's
// no point loading the -keys module even when a bluetooth keyboard may be
// available.
return !(Y.UA.ios || Y.UA.android);
},
"trigger": "autocomplete-list"
});
// graphics-svg
add('load', '3', {
"name": "graphics-svg",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return svg && (useSVG || !canvas);
},
"trigger": "graphics"
});
// editor-para-ie
add('load', '4', {
"name": "editor-para-ie",
"trigger": "editor-para",
"ua": "ie",
"when": "instead"
});
// graphics-vml-default
add('load', '5', {
"name": "graphics-vml-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
// graphics-svg-default
add('load', '6', {
"name": "graphics-svg-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return svg && (useSVG || !canvas);
},
"trigger": "graphics"
});
// history-hash-ie
add('load', '7', {
"name": "history-hash-ie",
"test": function (Y) {
var docMode = Y.config.doc && Y.config.doc.documentMode;
return Y.UA.ie && (!('onhashchange' in Y.config.win) ||
!docMode || docMode < 8);
},
"trigger": "history-hash"
});
// transition-timer
add('load', '8', {
"name": "transition-timer",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
node = (DOCUMENT) ? DOCUMENT.documentElement: null,
ret = true;
if (node && node.style) {
ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style);
}
return ret;
},
"trigger": "transition"
});
// dom-style-ie
add('load', '9', {
"name": "dom-style-ie",
"test": function (Y) {
var testFeature = Y.Features.test,
addFeature = Y.Features.add,
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
ret = false;
addFeature('style', 'computedStyle', {
test: function() {
return WINDOW && 'getComputedStyle' in WINDOW;
}
});
addFeature('style', 'opacity', {
test: function() {
return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style;
}
});
ret = (!testFeature('style', 'opacity') &&
!testFeature('style', 'computedStyle'));
return ret;
},
"trigger": "dom-style"
});
// selector-css2
add('load', '10', {
"name": "selector-css2",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
ret = DOCUMENT && !('querySelectorAll' in DOCUMENT);
return ret;
},
"trigger": "selector"
});
// widget-base-ie
add('load', '11', {
"name": "widget-base-ie",
"trigger": "widget-base",
"ua": "ie"
});
// event-base-ie
add('load', '12', {
"name": "event-base-ie",
"test": function(Y) {
var imp = Y.config.doc && Y.config.doc.implementation;
return (imp && (!imp.hasFeature('Events', '2.0')));
},
"trigger": "node-base"
});
// dd-gestures
add('load', '13', {
"name": "dd-gestures",
"test": function(Y) {
return ((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.chrome && Y.UA.chrome < 6));
},
"trigger": "dd-drag"
});
// scrollview-base-ie
add('load', '14', {
"name": "scrollview-base-ie",
"trigger": "scrollview-base",
"ua": "ie"
});
// app-transitions-native
add('load', '15', {
"name": "app-transitions-native",
"test": function (Y) {
var doc = Y.config.doc,
node = doc ? doc.documentElement : null;
if (node && node.style) {
return ('MozTransition' in node.style || 'WebkitTransition' in node.style);
}
return false;
},
"trigger": "app-transitions"
});
// graphics-canvas
add('load', '16', {
"name": "graphics-canvas",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d"));
},
"trigger": "graphics"
});
// graphics-vml
add('load', '17', {
"name": "graphics-vml",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('intl-base', function(Y) {
/**
* The Intl utility provides a central location for managing sets of
* localized resources (strings and formatting patterns).
*
* @class Intl
* @uses EventTarget
* @static
*/
var SPLIT_REGEX = /[, ]/;
Y.mix(Y.namespace('Intl'), {
/**
* Returns the language among those available that
* best matches the preferred language list, using the Lookup
* algorithm of BCP 47.
* If none of the available languages meets the user's preferences,
* then "" is returned.
* Extended language ranges are not supported.
*
* @method lookupBestLang
* @param {String[] | String} preferredLanguages The list of preferred
* languages in descending preference order, represented as BCP 47
* language tags. A string array or a comma-separated list.
* @param {String[]} availableLanguages The list of languages
* that the application supports, represented as BCP 47 language
* tags.
*
* @return {String} The available language that best matches the
* preferred language list, or "".
* @since 3.1.0
*/
lookupBestLang: function(preferredLanguages, availableLanguages) {
var i, language, result, index;
// check whether the list of available languages contains language;
// if so return it
function scan(language) {
var i;
for (i = 0; i < availableLanguages.length; i += 1) {
if (language.toLowerCase() ===
availableLanguages[i].toLowerCase()) {
return availableLanguages[i];
}
}
}
if (Y.Lang.isString(preferredLanguages)) {
preferredLanguages = preferredLanguages.split(SPLIT_REGEX);
}
for (i = 0; i < preferredLanguages.length; i += 1) {
language = preferredLanguages[i];
if (!language || language === '*') {
continue;
}
// check the fallback sequence for one language
while (language.length > 0) {
result = scan(language);
if (result) {
return result;
} else {
index = language.lastIndexOf('-');
if (index >= 0) {
language = language.substring(0, index);
// one-character subtags get cut along with the
// following subtag
if (index >= 2 && language.charAt(index - 2) === '-') {
language = language.substring(0, index - 2);
}
} else {
// nothing available for this language
break;
}
}
}
}
return '';
}
});
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('yui-log', function(Y) {
/**
* Provides console log capability and exposes a custom event for
* console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-log
*/
var INSTANCE = Y,
LOGEVENT = 'yui:log',
UNDEFINED = 'undefined',
LEVELS = { debug: 1,
info: 1,
warn: 1,
error: 1 };
/**
* If the 'debug' config is true, a 'yui:log' event will be
* dispatched, which the Console widget and anything else
* can consume. If the 'useBrowserConsole' config is true, it will
* write to the browser console if available. YUI-specific log
* messages will only be present in the -debug versions of the
* JS files. The build system is supposed to remove log statements
* from the raw and minified versions of the files.
*
* @method log
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.log = function(msg, cat, src, silent) {
var bail, excl, incl, m, f,
Y = INSTANCE,
c = Y.config,
publisher = (Y.fire) ? Y : YUI.Env.globalEvents;
// suppress log message if the config is off or the event stack
// or the event call stack contains a consumer of the yui:log event
if (c.debug) {
// apply source filters
if (src) {
excl = c.logExclude;
incl = c.logInclude;
if (incl && !(src in incl)) {
bail = 1;
} else if (incl && (src in incl)) {
bail = !incl[src];
} else if (excl && (src in excl)) {
bail = excl[src];
}
}
if (!bail) {
if (c.useBrowserConsole) {
m = (src) ? src + ': ' + msg : msg;
if (Y.Lang.isFunction(c.logFn)) {
c.logFn.call(Y, msg, cat, src);
} else if (typeof console != UNDEFINED && console.log) {
f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log';
console[f](m);
} else if (typeof opera != UNDEFINED) {
opera.postError(m);
}
}
if (publisher && !silent) {
if (publisher == Y && (!publisher.getEvent(LOGEVENT))) {
publisher.publish(LOGEVENT, {
broadcast: 2
});
}
publisher.fire(LOGEVENT, {
msg: msg,
cat: cat,
src: src
});
}
}
}
return Y;
};
/**
* Write a system message. This message will be preserved in the
* minified and raw versions of the YUI files, unlike log statements.
* @method message
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.message = function() {
return INSTANCE.log.apply(INSTANCE, arguments);
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('yui-later', function(Y) {
/**
* Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-later
*/
var NO_ARGS = [];
/**
* Executes the supplied function in the context of the supplied
* object 'when' milliseconds later. Executes the function a
* single time unless periodic is set to true.
* @for YUI
* @method later
* @param when {int} the number of milliseconds to wait until the fn
* is executed.
* @param o the context object.
* @param fn {Function|String} the function to execute or the name of
* the method in the 'o' object to execute.
* @param data [Array] data that is provided to the function. This
* accepts either a single item or an array. If an array is provided,
* the function is executed with one parameter for each array item.
* If you need to pass a single array parameter, it needs to be wrapped
* in an array [myarray].
*
* Note: native methods in IE may not have the call and apply methods.
* In this case, it will work, but you are limited to four arguments.
*
* @param periodic {boolean} if true, executes continuously at supplied
* interval until canceled.
* @return {object} a timer object. Call the cancel() method on this
* object to stop the timer.
*/
Y.later = function(when, o, fn, data, periodic) {
when = when || 0;
data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS;
o = o || Y.config.win || Y;
var cancelled = false,
method = (o && Y.Lang.isString(fn)) ? o[fn] : fn,
wrapper = function() {
// IE 8- may execute a setInterval callback one last time
// after clearInterval was called, so in order to preserve
// the cancel() === no more runny-run, we have to jump through
// an extra hoop.
if (!cancelled) {
if (!method.apply) {
method(data[0], data[1], data[2], data[3]);
} else {
method.apply(o, data || NO_ARGS);
}
}
},
id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when);
return {
id: id,
interval: periodic,
cancel: function() {
cancelled = true;
if (this.interval) {
clearInterval(id);
} else {
clearTimeout(id);
}
}
};
};
Y.Lang.later = Y.later;
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','intl-base','yui-log','yui-later']});
YUI.add('oop', function(Y) {
/**
Adds object inheritance and manipulation utilities to the YUI instance. This
module is required by most YUI components.
@module oop
**/
var L = Y.Lang,
A = Y.Array,
OP = Object.prototype,
CLONE_MARKER = '_~yuim~_',
hasOwn = OP.hasOwnProperty,
toString = OP.toString;
function dispatch(o, f, c, proto, action) {
if (o && o[action] && o !== Y) {
return o[action].call(o, f, c);
} else {
switch (A.test(o)) {
case 1:
return A[action](o, f, c);
case 2:
return A[action](Y.Array(o, 0, true), f, c);
default:
return Y.Object[action](o, f, c, proto);
}
}
}
/**
Augments the _receiver_ with prototype properties from the _supplier_. The
receiver may be a constructor function or an object. The supplier must be a
constructor function.
If the _receiver_ is an object, then the _supplier_ constructor will be called
immediately after _receiver_ is augmented, with _receiver_ as the `this` object.
If the _receiver_ is a constructor function, then all prototype methods of
_supplier_ that are copied to _receiver_ will be sequestered, and the
_supplier_ constructor will not be called immediately. The first time any
sequestered method is called on the _receiver_'s prototype, all sequestered
methods will be immediately copied to the _receiver_'s prototype, the
_supplier_'s constructor will be executed, and finally the newly unsequestered
method that was called will be executed.
This sequestering logic sounds like a bunch of complicated voodoo, but it makes
it cheap to perform frequent augmentation by ensuring that suppliers'
constructors are only called if a supplied method is actually used. If none of
the supplied methods is ever used, then there's no need to take the performance
hit of calling the _supplier_'s constructor.
@method augment
@param {Function|Object} receiver Object or function to be augmented.
@param {Function} supplier Function that supplies the prototype properties with
which to augment the _receiver_.
@param {Boolean} [overwrite=false] If `true`, properties already on the receiver
will be overwritten if found on the supplier's prototype.
@param {String[]} [whitelist] An array of property names. If specified,
only the whitelisted prototype properties will be applied to the receiver, and
all others will be ignored.
@param {Array|any} [args] Argument or array of arguments to pass to the
supplier's constructor when initializing.
@return {Function} Augmented object.
@for YUI
**/
Y.augment = function (receiver, supplier, overwrite, whitelist, args) {
var rProto = receiver.prototype,
sequester = rProto && supplier,
sProto = supplier.prototype,
to = rProto || receiver,
copy,
newPrototype,
replacements,
sequestered,
unsequester;
args = args ? Y.Array(args) : [];
if (sequester) {
newPrototype = {};
replacements = {};
sequestered = {};
copy = function (value, key) {
if (overwrite || !(key in rProto)) {
if (toString.call(value) === '[object Function]') {
sequestered[key] = value;
newPrototype[key] = replacements[key] = function () {
return unsequester(this, value, arguments);
};
} else {
newPrototype[key] = value;
}
}
};
unsequester = function (instance, fn, fnArgs) {
// Unsequester all sequestered functions.
for (var key in sequestered) {
if (hasOwn.call(sequestered, key)
&& instance[key] === replacements[key]) {
instance[key] = sequestered[key];
}
}
// Execute the supplier constructor.
supplier.apply(instance, args);
// Finally, execute the original sequestered function.
return fn.apply(instance, fnArgs);
};
if (whitelist) {
Y.Array.each(whitelist, function (name) {
if (name in sProto) {
copy(sProto[name], name);
}
});
} else {
Y.Object.each(sProto, copy, null, true);
}
}
Y.mix(to, newPrototype || sProto, overwrite, whitelist);
if (!sequester) {
supplier.apply(to, args);
}
return receiver;
};
/**
* Copies object properties from the supplier to the receiver. If the target has
* the property, and the property is an object, the target object will be
* augmented with the supplier's value.
*
* @method aggregate
* @param {Object} receiver Object to receive the augmentation.
* @param {Object} supplier Object that supplies the properties with which to
* augment the receiver.
* @param {Boolean} [overwrite=false] If `true`, properties already on the receiver
* will be overwritten if found on the supplier.
* @param {String[]} [whitelist] Whitelist. If supplied, only properties in this
* list will be applied to the receiver.
* @return {Object} Augmented object.
*/
Y.aggregate = function(r, s, ov, wl) {
return Y.mix(r, s, ov, wl, 0, true);
};
/**
* Utility to set up the prototype, constructor and superclass properties to
* support an inheritance strategy that can chain constructors and methods.
* Static members will not be inherited.
*
* @method extend
* @param {function} r the object to modify.
* @param {function} s the object to inherit.
* @param {object} px prototype properties to add/override.
* @param {object} sx static properties to add/override.
* @return {object} the extended object.
*/
Y.extend = function(r, s, px, sx) {
if (!s || !r) {
Y.error('extend failed, verify dependencies');
}
var sp = s.prototype, rp = Y.Object(sp);
r.prototype = rp;
rp.constructor = r;
r.superclass = sp;
// assign constructor property
if (s != Object && sp.constructor == OP.constructor) {
sp.constructor = s;
}
// add prototype overrides
if (px) {
Y.mix(rp, px, true);
}
// add object overrides
if (sx) {
Y.mix(r, sx, true);
}
return r;
};
/**
* Executes the supplied function for each item in
* a collection. Supports arrays, objects, and
* NodeLists
* @method each
* @param {object} o the object to iterate.
* @param {function} f the function to execute. This function
* receives the value, key, and object as parameters.
* @param {object} c the execution context for the function.
* @param {boolean} proto if true, prototype properties are
* iterated on objects.
* @return {YUI} the YUI instance.
*/
Y.each = function(o, f, c, proto) {
return dispatch(o, f, c, proto, 'each');
};
/**
* Executes the supplied function for each item in
* a collection. The operation stops if the function
* returns true. Supports arrays, objects, and
* NodeLists.
* @method some
* @param {object} o the object to iterate.
* @param {function} f the function to execute. This function
* receives the value, key, and object as parameters.
* @param {object} c the execution context for the function.
* @param {boolean} proto if true, prototype properties are
* iterated on objects.
* @return {boolean} true if the function ever returns true,
* false otherwise.
*/
Y.some = function(o, f, c, proto) {
return dispatch(o, f, c, proto, 'some');
};
/**
* Deep object/array copy. Function clones are actually
* wrappers around the original function.
* Array-like objects are treated as arrays.
* Primitives are returned untouched. Optionally, a
* function can be provided to handle other data types,
* filter keys, validate values, etc.
*
* @method clone
* @param {object} o what to clone.
* @param {boolean} safe if true, objects will not have prototype
* items from the source. If false, they will. In this case, the
* original is initially protected, but the clone is not completely
* immune from changes to the source object prototype. Also, cloned
* prototype items that are deleted from the clone will result
* in the value of the source prototype being exposed. If operating
* on a non-safe clone, items should be nulled out rather than deleted.
* @param {function} f optional function to apply to each item in a
* collection; it will be executed prior to applying the value to
* the new object. Return false to prevent the copy.
* @param {object} c optional execution context for f.
* @param {object} owner Owner object passed when clone is iterating
* an object. Used to set up context for cloned functions.
* @param {object} cloned hash of previously cloned objects to avoid
* multiple clones.
* @return {Array|Object} the cloned object.
*/
Y.clone = function(o, safe, f, c, owner, cloned) {
if (!L.isObject(o)) {
return o;
}
// @todo cloning YUI instances doesn't currently work
if (Y.instanceOf(o, YUI)) {
return o;
}
var o2, marked = cloned || {}, stamp,
yeach = Y.each;
switch (L.type(o)) {
case 'date':
return new Date(o);
case 'regexp':
// if we do this we need to set the flags too
// return new RegExp(o.source);
return o;
case 'function':
// o2 = Y.bind(o, owner);
// break;
return o;
case 'array':
o2 = [];
break;
default:
// #2528250 only one clone of a given object should be created.
if (o[CLONE_MARKER]) {
return marked[o[CLONE_MARKER]];
}
stamp = Y.guid();
o2 = (safe) ? {} : Y.Object(o);
o[CLONE_MARKER] = stamp;
marked[stamp] = o;
}
// #2528250 don't try to clone element properties
if (!o.addEventListener && !o.attachEvent) {
yeach(o, function(v, k) {
if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) {
if (k !== CLONE_MARKER) {
if (k == 'prototype') {
// skip the prototype
// } else if (o[k] === o) {
// this[k] = this;
} else {
this[k] =
Y.clone(v, safe, f, c, owner || o, marked);
}
}
}
}, o2);
}
if (!cloned) {
Y.Object.each(marked, function(v, k) {
if (v[CLONE_MARKER]) {
try {
delete v[CLONE_MARKER];
} catch (e) {
v[CLONE_MARKER] = null;
}
}
}, this);
marked = null;
}
return o2;
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the beginning of the arguments collection the
* supplied to the function.
*
* @method bind
* @param {Function|String} f the function to bind, or a function name
* to execute on the context object.
* @param {object} c the execution context.
* @param {any} args* 0..n arguments to include before the arguments the
* function is executed with.
* @return {function} the wrapped function.
*/
Y.bind = function(f, c) {
var xargs = arguments.length > 2 ?
Y.Array(arguments, 2, true) : null;
return function() {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ?
xargs.concat(Y.Array(arguments, 0, true)) : arguments;
return fn.apply(c || fn, args);
};
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the end of the arguments the function
* is executed with.
*
* @method rbind
* @param {Function|String} f the function to bind, or a function name
* to execute on the context object.
* @param {object} c the execution context.
* @param {any} args* 0..n arguments to append to the end of
* arguments collection supplied to the function.
* @return {function} the wrapped function.
*/
Y.rbind = function(f, c) {
var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null;
return function() {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ?
Y.Array(arguments, 0, true).concat(xargs) : arguments;
return fn.apply(c || fn, args);
};
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('features', function(Y) {
var feature_tests = {};
/**
Contains the core of YUI's feature test architecture.
@module features
*/
/**
* Feature detection
* @class Features
* @static
*/
Y.mix(Y.namespace('Features'), {
/**
* Object hash of all registered feature tests
* @property tests
* @type Object
*/
tests: feature_tests,
/**
* Add a test to the system
*
* ```
* Y.Features.add("load", "1", {});
* ```
*
* @method add
* @param {String} cat The category, right now only 'load' is supported
* @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3
* @param {Object} o Object containing test properties
* @param {String} o.name The name of the test
* @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance
* @param {String} o.trigger The module that triggers this test.
*/
add: function(cat, name, o) {
feature_tests[cat] = feature_tests[cat] || {};
feature_tests[cat][name] = o;
},
/**
* Execute all tests of a given category and return the serialized results
*
* ```
* caps=1:1;2:1;3:0
* ```
* @method all
* @param {String} cat The category to execute
* @param {Array} args The arguments to pass to the test function
* @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0
*/
all: function(cat, args) {
var cat_o = feature_tests[cat],
// results = {};
result = [];
if (cat_o) {
Y.Object.each(cat_o, function(v, k) {
result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0));
});
}
return (result.length) ? result.join(';') : '';
},
/**
* Run a sepecific test and return a Boolean response.
*
* ```
* Y.Features.test("load", "1");
* ```
*
* @method test
* @param {String} cat The category of the test to run
* @param {String} name The name of the test to run
* @param {Array} args The arguments to pass to the test function
* @return {Boolean} True or false if the test passed/failed.
*/
test: function(cat, name, args) {
args = args || [];
var result, ua, test,
cat_o = feature_tests[cat],
feature = cat_o && cat_o[name];
if (!feature) {
Y.log('Feature test ' + cat + ', ' + name + ' not found');
} else {
result = feature.result;
if (Y.Lang.isUndefined(result)) {
ua = feature.ua;
if (ua) {
result = (Y.UA[ua]);
}
test = feature.test;
if (test && ((!ua) || result)) {
result = test.apply(Y, args);
}
feature.result = result;
}
}
return result;
}
});
// Y.Features.add("load", "1", {});
// Y.Features.test("load", "1");
// caps=1:1;2:0;3:1;
/* This file is auto-generated by src/loader/scripts/meta_join.py */
var add = Y.Features.add;
// io-nodejs
add('load', '0', {
"name": "io-nodejs",
"trigger": "io-base",
"ua": "nodejs"
});
// graphics-canvas-default
add('load', '1', {
"name": "graphics-canvas-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d"));
},
"trigger": "graphics"
});
// autocomplete-list-keys
add('load', '2', {
"name": "autocomplete-list-keys",
"test": function (Y) {
// Only add keyboard support to autocomplete-list if this doesn't appear to
// be an iOS or Android-based mobile device.
//
// There's currently no feasible way to actually detect whether a device has
// a hardware keyboard, so this sniff will have to do. It can easily be
// overridden by manually loading the autocomplete-list-keys module.
//
// Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari
// doesn't fire the keyboard events used by AutoCompleteList, so there's
// no point loading the -keys module even when a bluetooth keyboard may be
// available.
return !(Y.UA.ios || Y.UA.android);
},
"trigger": "autocomplete-list"
});
// graphics-svg
add('load', '3', {
"name": "graphics-svg",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return svg && (useSVG || !canvas);
},
"trigger": "graphics"
});
// editor-para-ie
add('load', '4', {
"name": "editor-para-ie",
"trigger": "editor-para",
"ua": "ie",
"when": "instead"
});
// graphics-vml-default
add('load', '5', {
"name": "graphics-vml-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
// graphics-svg-default
add('load', '6', {
"name": "graphics-svg-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return svg && (useSVG || !canvas);
},
"trigger": "graphics"
});
// history-hash-ie
add('load', '7', {
"name": "history-hash-ie",
"test": function (Y) {
var docMode = Y.config.doc && Y.config.doc.documentMode;
return Y.UA.ie && (!('onhashchange' in Y.config.win) ||
!docMode || docMode < 8);
},
"trigger": "history-hash"
});
// transition-timer
add('load', '8', {
"name": "transition-timer",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
node = (DOCUMENT) ? DOCUMENT.documentElement: null,
ret = true;
if (node && node.style) {
ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style);
}
return ret;
},
"trigger": "transition"
});
// dom-style-ie
add('load', '9', {
"name": "dom-style-ie",
"test": function (Y) {
var testFeature = Y.Features.test,
addFeature = Y.Features.add,
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
ret = false;
addFeature('style', 'computedStyle', {
test: function() {
return WINDOW && 'getComputedStyle' in WINDOW;
}
});
addFeature('style', 'opacity', {
test: function() {
return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style;
}
});
ret = (!testFeature('style', 'opacity') &&
!testFeature('style', 'computedStyle'));
return ret;
},
"trigger": "dom-style"
});
// selector-css2
add('load', '10', {
"name": "selector-css2",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
ret = DOCUMENT && !('querySelectorAll' in DOCUMENT);
return ret;
},
"trigger": "selector"
});
// widget-base-ie
add('load', '11', {
"name": "widget-base-ie",
"trigger": "widget-base",
"ua": "ie"
});
// event-base-ie
add('load', '12', {
"name": "event-base-ie",
"test": function(Y) {
var imp = Y.config.doc && Y.config.doc.implementation;
return (imp && (!imp.hasFeature('Events', '2.0')));
},
"trigger": "node-base"
});
// dd-gestures
add('load', '13', {
"name": "dd-gestures",
"test": function(Y) {
return ((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.chrome && Y.UA.chrome < 6));
},
"trigger": "dd-drag"
});
// scrollview-base-ie
add('load', '14', {
"name": "scrollview-base-ie",
"trigger": "scrollview-base",
"ua": "ie"
});
// app-transitions-native
add('load', '15', {
"name": "app-transitions-native",
"test": function (Y) {
var doc = Y.config.doc,
node = doc ? doc.documentElement : null;
if (node && node.style) {
return ('MozTransition' in node.style || 'WebkitTransition' in node.style);
}
return false;
},
"trigger": "app-transitions"
});
// graphics-canvas
add('load', '16', {
"name": "graphics-canvas",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d"));
},
"trigger": "graphics"
});
// graphics-vml
add('load', '17', {
"name": "graphics-vml",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('dom-core', function(Y) {
var NODE_TYPE = 'nodeType',
OWNER_DOCUMENT = 'ownerDocument',
DOCUMENT_ELEMENT = 'documentElement',
DEFAULT_VIEW = 'defaultView',
PARENT_WINDOW = 'parentWindow',
TAG_NAME = 'tagName',
PARENT_NODE = 'parentNode',
PREVIOUS_SIBLING = 'previousSibling',
NEXT_SIBLING = 'nextSibling',
CONTAINS = 'contains',
COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition',
EMPTY_ARRAY = [],
/**
* The DOM utility provides a cross-browser abtraction layer
* normalizing DOM tasks, and adds extra helper functionality
* for other common tasks.
* @module dom
* @main dom
* @submodule dom-base
* @for DOM
*
*/
/**
* Provides DOM helper methods.
* @class DOM
*
*/
Y_DOM = {
/**
* Returns the HTMLElement with the given ID (Wrapper for document.getElementById).
* @method byId
* @param {String} id the id attribute
* @param {Object} doc optional The document to search. Defaults to current document
* @return {HTMLElement | null} The HTMLElement with the id, or null if none found.
*/
byId: function(id, doc) {
// handle dupe IDs and IE name collision
return Y_DOM.allById(id, doc)[0] || null;
},
getId: function(node) {
var id;
// HTMLElement returned from FORM when INPUT name === "id"
// IE < 8: HTMLCollection returned when INPUT id === "id"
// via both getAttribute and form.id
if (node.id && !node.id.tagName && !node.id.item) {
id = node.id;
} else if (node.attributes && node.attributes.id) {
id = node.attributes.id.value;
}
return id;
},
setId: function(node, id) {
if (node.setAttribute) {
node.setAttribute('id', id);
} else {
node.id = id;
}
},
/*
* Finds the ancestor of the element.
* @method ancestor
* @param {HTMLElement} element The html element.
* @param {Function} fn optional An optional boolean test to apply.
* The optional function is passed the current DOM node being tested as its only argument.
* If no function is given, the parentNode is returned.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* @return {HTMLElement | null} The matching DOM node or null if none found.
*/
ancestor: function(element, fn, testSelf, stopFn) {
var ret = null;
if (testSelf) {
ret = (!fn || fn(element)) ? element : null;
}
return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn);
},
/*
* Finds the ancestors of the element.
* @method ancestors
* @param {HTMLElement} element The html element.
* @param {Function} fn optional An optional boolean test to apply.
* The optional function is passed the current DOM node being tested as its only argument.
* If no function is given, all ancestors are returned.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* @return {Array} An array containing all matching DOM nodes.
*/
ancestors: function(element, fn, testSelf, stopFn) {
var ancestor = element,
ret = [];
while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) {
testSelf = false;
if (ancestor) {
ret.unshift(ancestor);
if (stopFn && stopFn(ancestor)) {
return ret;
}
}
}
return ret;
},
/**
* Searches the element by the given axis for the first matching element.
* @method elementByAxis
* @param {HTMLElement} element The html element.
* @param {String} axis The axis to search (parentNode, nextSibling, previousSibling).
* @param {Function} fn optional An optional boolean test to apply.
* @param {Boolean} all optional Whether all node types should be returned, or just element nodes.
* The optional function is passed the current HTMLElement being tested as its only argument.
* If no function is given, the first element is returned.
* @return {HTMLElement | null} The matching element or null if none found.
*/
elementByAxis: function(element, axis, fn, all, stopAt) {
while (element && (element = element[axis])) { // NOTE: assignment
if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) {
return element;
}
if (stopAt && stopAt(element)) {
return null;
}
}
return null;
},
/**
* Determines whether or not one HTMLElement is or contains another HTMLElement.
* @method contains
* @param {HTMLElement} element The containing html element.
* @param {HTMLElement} needle The html element that may be contained.
* @return {Boolean} Whether or not the element is or contains the needle.
*/
contains: function(element, needle) {
var ret = false;
if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) {
ret = false;
} else if (element[CONTAINS]) {
if (Y.UA.opera || needle[NODE_TYPE] === 1) { // IE & SAF contains fail if needle not an ELEMENT_NODE
ret = element[CONTAINS](needle);
} else {
ret = Y_DOM._bruteContains(element, needle);
}
} else if (element[COMPARE_DOCUMENT_POSITION]) { // gecko
if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) {
ret = true;
}
}
return ret;
},
/**
* Determines whether or not the HTMLElement is part of the document.
* @method inDoc
* @param {HTMLElement} element The containing html element.
* @param {HTMLElement} doc optional The document to check.
* @return {Boolean} Whether or not the element is attached to the document.
*/
inDoc: function(element, doc) {
var ret = false,
rootNode;
if (element && element.nodeType) {
(doc) || (doc = element[OWNER_DOCUMENT]);
rootNode = doc[DOCUMENT_ELEMENT];
// contains only works with HTML_ELEMENT
if (rootNode && rootNode.contains && element.tagName) {
ret = rootNode.contains(element);
} else {
ret = Y_DOM.contains(rootNode, element);
}
}
return ret;
},
allById: function(id, root) {
root = root || Y.config.doc;
var nodes = [],
ret = [],
i,
node;
if (root.querySelectorAll) {
ret = root.querySelectorAll('[id="' + id + '"]');
} else if (root.all) {
nodes = root.all(id);
if (nodes) {
// root.all may return HTMLElement or HTMLCollection.
// some elements are also HTMLCollection (FORM, SELECT).
if (nodes.nodeName) {
if (nodes.id === id) { // avoid false positive on name
ret.push(nodes);
nodes = EMPTY_ARRAY; // done, no need to filter
} else { // prep for filtering
nodes = [nodes];
}
}
if (nodes.length) {
// filter out matches on node.name
// and element.id as reference to element with id === 'id'
for (i = 0; node = nodes[i++];) {
if (node.id === id ||
(node.attributes && node.attributes.id &&
node.attributes.id.value === id)) {
ret.push(node);
}
}
}
}
} else {
ret = [Y_DOM._getDoc(root).getElementById(id)];
}
return ret;
},
isWindow: function(obj) {
return !!(obj && obj.alert && obj.document);
},
_removeChildNodes: function(node) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
},
siblings: function(node, fn) {
var nodes = [],
sibling = node;
while ((sibling = sibling[PREVIOUS_SIBLING])) {
if (sibling[TAG_NAME] && (!fn || fn(sibling))) {
nodes.unshift(sibling);
}
}
sibling = node;
while ((sibling = sibling[NEXT_SIBLING])) {
if (sibling[TAG_NAME] && (!fn || fn(sibling))) {
nodes.push(sibling);
}
}
return nodes;
},
/**
* Brute force version of contains.
* Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc).
* @method _bruteContains
* @private
* @param {HTMLElement} element The containing html element.
* @param {HTMLElement} needle The html element that may be contained.
* @return {Boolean} Whether or not the element is or contains the needle.
*/
_bruteContains: function(element, needle) {
while (needle) {
if (element === needle) {
return true;
}
needle = needle.parentNode;
}
return false;
},
// TODO: move to Lang?
/**
* Memoizes dynamic regular expressions to boost runtime performance.
* @method _getRegExp
* @private
* @param {String} str The string to convert to a regular expression.
* @param {String} flags optional An optinal string of flags.
* @return {RegExp} An instance of RegExp
*/
_getRegExp: function(str, flags) {
flags = flags || '';
Y_DOM._regexCache = Y_DOM._regexCache || {};
if (!Y_DOM._regexCache[str + flags]) {
Y_DOM._regexCache[str + flags] = new RegExp(str, flags);
}
return Y_DOM._regexCache[str + flags];
},
// TODO: make getDoc/Win true privates?
/**
* returns the appropriate document.
* @method _getDoc
* @private
* @param {HTMLElement} element optional Target element.
* @return {Object} The document for the given element or the default document.
*/
_getDoc: function(element) {
var doc = Y.config.doc;
if (element) {
doc = (element[NODE_TYPE] === 9) ? element : // element === document
element[OWNER_DOCUMENT] || // element === DOM node
element.document || // element === window
Y.config.doc; // default
}
return doc;
},
/**
* returns the appropriate window.
* @method _getWin
* @private
* @param {HTMLElement} element optional Target element.
* @return {Object} The window for the given element or the default window.
*/
_getWin: function(element) {
var doc = Y_DOM._getDoc(element);
return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win;
},
_batch: function(nodes, fn, arg1, arg2, arg3, etc) {
fn = (typeof fn === 'string') ? Y_DOM[fn] : fn;
var result,
i = 0,
node,
ret;
if (fn && nodes) {
while ((node = nodes[i++])) {
result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc);
if (typeof result !== 'undefined') {
(ret) || (ret = []);
ret.push(result);
}
}
}
return (typeof ret !== 'undefined') ? ret : nodes;
},
generateID: function(el) {
var id = el.id;
if (!id) {
id = Y.stamp(el);
el.id = id;
}
return id;
}
};
Y.DOM = Y_DOM;
}, '@VERSION@' ,{requires:['oop','features']});
YUI.add('dom-base', function(Y) {
/**
* @for DOM
* @module dom
*/
var documentElement = Y.config.doc.documentElement,
Y_DOM = Y.DOM,
TAG_NAME = 'tagName',
OWNER_DOCUMENT = 'ownerDocument',
EMPTY_STRING = '',
addFeature = Y.Features.add,
testFeature = Y.Features.test;
Y.mix(Y_DOM, {
/**
* Returns the text content of the HTMLElement.
* @method getText
* @param {HTMLElement} element The html element.
* @return {String} The text content of the element (includes text of any descending elements).
*/
getText: (documentElement.textContent !== undefined) ?
function(element) {
var ret = '';
if (element) {
ret = element.textContent;
}
return ret || '';
} : function(element) {
var ret = '';
if (element) {
ret = element.innerText || element.nodeValue; // might be a textNode
}
return ret || '';
},
/**
* Sets the text content of the HTMLElement.
* @method setText
* @param {HTMLElement} element The html element.
* @param {String} content The content to add.
*/
setText: (documentElement.textContent !== undefined) ?
function(element, content) {
if (element) {
element.textContent = content;
}
} : function(element, content) {
if ('innerText' in element) {
element.innerText = content;
} else if ('nodeValue' in element) {
element.nodeValue = content;
}
},
CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8
'for': 'htmlFor',
'class': 'className'
} : { // w3c
'htmlFor': 'for',
'className': 'class'
},
/**
* Provides a normalized attribute interface.
* @method setAttribute
* @param {HTMLElement} el The target element for the attribute.
* @param {String} attr The attribute to set.
* @param {String} val The value of the attribute.
*/
setAttribute: function(el, attr, val, ieAttr) {
if (el && attr && el.setAttribute) {
attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr;
el.setAttribute(attr, val, ieAttr);
}
else { Y.log('bad input to setAttribute', 'warn', 'dom'); }
},
/**
* Provides a normalized attribute interface.
* @method getAttribute
* @param {HTMLElement} el The target element for the attribute.
* @param {String} attr The attribute to get.
* @return {String} The current value of the attribute.
*/
getAttribute: function(el, attr, ieAttr) {
ieAttr = (ieAttr !== undefined) ? ieAttr : 2;
var ret = '';
if (el && attr && el.getAttribute) {
attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr;
ret = el.getAttribute(attr, ieAttr);
if (ret === null) {
ret = ''; // per DOM spec
}
}
else { Y.log('bad input to getAttribute', 'warn', 'dom'); }
return ret;
},
VALUE_SETTERS: {},
VALUE_GETTERS: {},
getValue: function(node) {
var ret = '', // TODO: return null?
getter;
if (node && node[TAG_NAME]) {
getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()];
if (getter) {
ret = getter(node);
} else {
ret = node.value;
}
}
// workaround for IE8 JSON stringify bug
// which converts empty string values to null
if (ret === EMPTY_STRING) {
ret = EMPTY_STRING; // for real
}
return (typeof ret === 'string') ? ret : '';
},
setValue: function(node, val) {
var setter;
if (node && node[TAG_NAME]) {
setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()];
if (setter) {
setter(node, val);
} else {
node.value = val;
}
}
},
creators: {}
});
addFeature('value-set', 'select', {
test: function() {
var node = Y.config.doc.createElement('select');
node.innerHTML = '<option>1</option><option>2</option>';
node.value = '2';
return (node.value && node.value === '2');
}
});
if (!testFeature('value-set', 'select')) {
Y_DOM.VALUE_SETTERS.select = function(node, val) {
for (var i = 0, options = node.getElementsByTagName('option'), option;
option = options[i++];) {
if (Y_DOM.getValue(option) === val) {
option.selected = true;
//Y_DOM.setAttribute(option, 'selected', 'selected');
break;
}
}
}
}
Y.mix(Y_DOM.VALUE_GETTERS, {
button: function(node) {
return (node.attributes && node.attributes.value) ? node.attributes.value.value : '';
}
});
Y.mix(Y_DOM.VALUE_SETTERS, {
// IE: node.value changes the button text, which should be handled via innerHTML
button: function(node, val) {
var attr = node.attributes.value;
if (!attr) {
attr = node[OWNER_DOCUMENT].createAttribute('value');
node.setAttributeNode(attr);
}
attr.value = val;
}
});
Y.mix(Y_DOM.VALUE_GETTERS, {
option: function(node) {
var attrs = node.attributes;
return (attrs.value && attrs.value.specified) ? node.value : node.text;
},
select: function(node) {
var val = node.value,
options = node.options;
if (options && options.length) {
// TODO: implement multipe select
if (node.multiple) {
Y.log('multiple select normalization not implemented', 'warn', 'DOM');
} else if (node.selectedIndex > -1) {
val = Y_DOM.getValue(options[node.selectedIndex]);
}
}
return val;
}
});
var addClass, hasClass, removeClass;
Y.mix(Y.DOM, {
/**
* Determines whether a DOM element has the given className.
* @method hasClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to search for
* @return {Boolean} Whether or not the element has the given class.
*/
hasClass: function(node, className) {
var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
return re.test(node.className);
},
/**
* Adds a class name to a given DOM element.
* @method addClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to add to the class attribute
*/
addClass: function(node, className) {
if (!Y.DOM.hasClass(node, className)) { // skip if already present
node.className = Y.Lang.trim([node.className, className].join(' '));
}
},
/**
* Removes a class name from a given element.
* @method removeClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to remove from the class attribute
*/
removeClass: function(node, className) {
if (className && hasClass(node, className)) {
node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' +
className + '(?:\\s+|$)'), ' '));
if ( hasClass(node, className) ) { // in case of multiple adjacent
removeClass(node, className);
}
}
},
/**
* Replace a class with another class for a given element.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @for DOM
* @param {HTMLElement} element The DOM element
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
*/
replaceClass: function(node, oldC, newC) {
//Y.log('replaceClass replacing ' + oldC + ' with ' + newC, 'info', 'Node');
removeClass(node, oldC); // remove first in case oldC === newC
addClass(node, newC);
},
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @for DOM
* @param {HTMLElement} element The DOM element
* @param {String} className the class name to be toggled
* @param {Boolean} addClass optional boolean to indicate whether class
* should be added or removed regardless of current state
*/
toggleClass: function(node, className, force) {
var add = (force !== undefined) ? force :
!(hasClass(node, className));
if (add) {
addClass(node, className);
} else {
removeClass(node, className);
}
}
});
hasClass = Y.DOM.hasClass;
removeClass = Y.DOM.removeClass;
addClass = Y.DOM.addClass;
var re_tag = /<([a-z]+)/i,
Y_DOM = Y.DOM,
addFeature = Y.Features.add,
testFeature = Y.Features.test,
creators = {},
createFromDIV = function(html, tag) {
var div = Y.config.doc.createElement('div'),
ret = true;
div.innerHTML = html;
if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) {
ret = false;
}
return ret;
},
re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/,
TABLE_OPEN = '<table>',
TABLE_CLOSE = '</table>';
Y.mix(Y.DOM, {
_fragClones: {},
_create: function(html, doc, tag) {
tag = tag || 'div';
var frag = Y_DOM._fragClones[tag];
if (frag) {
frag = frag.cloneNode(false);
} else {
frag = Y_DOM._fragClones[tag] = doc.createElement(tag);
}
frag.innerHTML = html;
return frag;
},
_children: function(node, tag) {
var i = 0,
children = node.children,
childNodes,
hasComments,
child;
if (children && children.tags) { // use tags filter when possible
if (tag) {
children = node.children.tags(tag);
} else { // IE leaks comments into children
hasComments = children.tags('!').length;
}
}
if (!children || (!children.tags && tag) || hasComments) {
childNodes = children || node.childNodes;
children = [];
while ((child = childNodes[i++])) {
if (child.nodeType === 1) {
if (!tag || tag === child.tagName) {
children.push(child);
}
}
}
}
return children || [];
},
/**
* Creates a new dom node using the provided markup string.
* @method create
* @param {String} html The markup used to create the element
* @param {HTMLDocument} doc An optional document context
* @return {HTMLElement|DocumentFragment} returns a single HTMLElement
* when creating one node, and a documentFragment when creating
* multiple nodes.
*/
create: function(html, doc) {
if (typeof html === 'string') {
html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML
}
doc = doc || Y.config.doc;
var m = re_tag.exec(html),
create = Y_DOM._create,
custom = creators,
ret = null,
creator,
tag, nodes;
if (html != undefined) { // not undefined or null
if (m && m[1]) {
creator = custom[m[1].toLowerCase()];
if (typeof creator === 'function') {
create = creator;
} else {
tag = creator;
}
}
nodes = create(html, doc, tag).childNodes;
if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment"
ret = nodes[0].parentNode.removeChild(nodes[0]);
} else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected)
if (nodes.length === 2) {
ret = nodes[0].nextSibling;
} else {
nodes[0].parentNode.removeChild(nodes[0]);
ret = Y_DOM._nl2frag(nodes, doc);
}
} else { // return multiple nodes as a fragment
ret = Y_DOM._nl2frag(nodes, doc);
}
}
return ret;
},
_nl2frag: function(nodes, doc) {
var ret = null,
i, len;
if (nodes && (nodes.push || nodes.item) && nodes[0]) {
doc = doc || nodes[0].ownerDocument;
ret = doc.createDocumentFragment();
if (nodes.item) { // convert live list to static array
nodes = Y.Array(nodes, 0, true);
}
for (i = 0, len = nodes.length; i < len; i++) {
ret.appendChild(nodes[i]);
}
} // else inline with log for minification
return ret;
},
/**
* Inserts content in a node at the given location
* @method addHTML
* @param {HTMLElement} node The node to insert into
* @param {HTMLElement | Array | HTMLCollection} content The content to be inserted
* @param {HTMLElement} where Where to insert the content
* If no "where" is given, content is appended to the node
* Possible values for "where"
* <dl>
* <dt>HTMLElement</dt>
* <dd>The element to insert before</dd>
* <dt>"replace"</dt>
* <dd>Replaces the existing HTML</dd>
* <dt>"before"</dt>
* <dd>Inserts before the existing HTML</dd>
* <dt>"before"</dt>
* <dd>Inserts content before the node</dd>
* <dt>"after"</dt>
* <dd>Inserts content after the node</dd>
* </dl>
*/
addHTML: function(node, content, where) {
var nodeParent = node.parentNode,
i = 0,
item,
ret = content,
newNode;
if (content != undefined) { // not null or undefined (maybe 0)
if (content.nodeType) { // DOM node, just add it
newNode = content;
} else if (typeof content == 'string' || typeof content == 'number') {
ret = newNode = Y_DOM.create(content);
} else if (content[0] && content[0].nodeType) { // array or collection
newNode = Y.config.doc.createDocumentFragment();
while ((item = content[i++])) {
newNode.appendChild(item); // append to fragment for insertion
}
}
}
if (where) {
if (newNode && where.parentNode) { // insert regardless of relationship to node
where.parentNode.insertBefore(newNode, where);
} else {
switch (where) {
case 'replace':
while (node.firstChild) {
node.removeChild(node.firstChild);
}
if (newNode) { // allow empty content to clear node
node.appendChild(newNode);
}
break;
case 'before':
if (newNode) {
nodeParent.insertBefore(newNode, node);
}
break;
case 'after':
if (newNode) {
if (node.nextSibling) { // IE errors if refNode is null
nodeParent.insertBefore(newNode, node.nextSibling);
} else {
nodeParent.appendChild(newNode);
}
}
break;
default:
if (newNode) {
node.appendChild(newNode);
}
}
}
} else if (newNode) {
node.appendChild(newNode);
}
return ret;
},
wrap: function(node, html) {
var parent = (html && html.nodeType) ? html : Y.DOM.create(html),
nodes = parent.getElementsByTagName('*');
if (nodes.length) {
parent = nodes[nodes.length - 1];
}
if (node.parentNode) {
node.parentNode.replaceChild(parent, node);
}
parent.appendChild(node);
},
unwrap: function(node) {
var parent = node.parentNode,
lastChild = parent.lastChild,
next = node,
grandparent;
if (parent) {
grandparent = parent.parentNode;
if (grandparent) {
node = parent.firstChild;
while (node !== lastChild) {
next = node.nextSibling;
grandparent.insertBefore(node, parent);
node = next;
}
grandparent.replaceChild(lastChild, parent);
} else {
parent.removeChild(node);
}
}
}
});
addFeature('innerhtml', 'table', {
test: function() {
var node = Y.config.doc.createElement('table');
try {
node.innerHTML = '<tbody></tbody>';
} catch(e) {
return false;
}
return (node.firstChild && node.firstChild.nodeName === 'TBODY');
}
});
addFeature('innerhtml-div', 'tr', {
test: function() {
return createFromDIV('<tr></tr>', 'tr');
}
});
addFeature('innerhtml-div', 'script', {
test: function() {
return createFromDIV('<script></script>', 'script');
}
});
if (!testFeature('innerhtml', 'table')) {
// TODO: thead/tfoot with nested tbody
// IE adds TBODY when creating TABLE elements (which may share this impl)
creators.tbody = function(html, doc) {
var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc),
tb = Y.DOM._children(frag, 'tbody')[0];
if (frag.children.length > 1 && tb && !re_tbody.test(html)) {
tb.parentNode.removeChild(tb); // strip extraneous tbody
}
return frag;
};
}
if (!testFeature('innerhtml-div', 'script')) {
creators.script = function(html, doc) {
var frag = doc.createElement('div');
frag.innerHTML = '-' + html;
frag.removeChild(frag.firstChild);
return frag;
}
creators.link = creators.style = creators.script;
}
if (!testFeature('innerhtml-div', 'tr')) {
Y.mix(creators, {
option: function(html, doc) {
return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc);
},
tr: function(html, doc) {
return Y_DOM.create('<tbody>' + html + '</tbody>', doc);
},
td: function(html, doc) {
return Y_DOM.create('<tr>' + html + '</tr>', doc);
},
col: function(html, doc) {
return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc);
},
tbody: 'table'
});
Y.mix(creators, {
legend: 'fieldset',
th: creators.td,
thead: creators.tbody,
tfoot: creators.tbody,
caption: creators.tbody,
colgroup: creators.tbody,
optgroup: creators.option
});
}
Y_DOM.creators = creators;
Y.mix(Y.DOM, {
/**
* Sets the width of the element to the given size, regardless
* of box model, border, padding, etc.
* @method setWidth
* @param {HTMLElement} element The DOM element.
* @param {String|Number} size The pixel height to size to
*/
setWidth: function(node, size) {
Y.DOM._setSize(node, 'width', size);
},
/**
* Sets the height of the element to the given size, regardless
* of box model, border, padding, etc.
* @method setHeight
* @param {HTMLElement} element The DOM element.
* @param {String|Number} size The pixel height to size to
*/
setHeight: function(node, size) {
Y.DOM._setSize(node, 'height', size);
},
_setSize: function(node, prop, val) {
val = (val > 0) ? val : 0;
var size = 0;
node.style[prop] = val + 'px';
size = (prop === 'height') ? node.offsetHeight : node.offsetWidth;
if (size > val) {
val = val - (size - val);
if (val < 0) {
val = 0;
}
node.style[prop] = val + 'px';
}
}
});
}, '@VERSION@' ,{requires:['dom-core']});
YUI.add('dom-style', function(Y) {
(function(Y) {
/**
* Add style management functionality to DOM.
* @module dom
* @submodule dom-style
* @for DOM
*/
var DOCUMENT_ELEMENT = 'documentElement',
DEFAULT_VIEW = 'defaultView',
OWNER_DOCUMENT = 'ownerDocument',
STYLE = 'style',
FLOAT = 'float',
CSS_FLOAT = 'cssFloat',
STYLE_FLOAT = 'styleFloat',
TRANSPARENT = 'transparent',
GET_COMPUTED_STYLE = 'getComputedStyle',
GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect',
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
UNDEFINED = undefined,
Y_DOM = Y.DOM,
TRANSFORM = 'transform',
VENDOR_TRANSFORM = [
'WebkitTransform',
'MozTransform',
'OTransform'
],
re_color = /color$/i,
re_unit = /width|height|top|left|right|bottom|margin|padding/i;
Y.Array.each(VENDOR_TRANSFORM, function(val) {
if (val in DOCUMENT[DOCUMENT_ELEMENT].style) {
TRANSFORM = val;
}
});
Y.mix(Y_DOM, {
DEFAULT_UNIT: 'px',
CUSTOM_STYLES: {
},
/**
* Sets a style property for a given element.
* @method setStyle
* @param {HTMLElement} An HTMLElement to apply the style to.
* @param {String} att The style property to set.
* @param {String|Number} val The value.
*/
setStyle: function(node, att, val, style) {
style = style || node.style;
var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES;
if (style) {
if (val === null || val === '') { // normalize unsetting
val = '';
} else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit
val += Y_DOM.DEFAULT_UNIT;
}
if (att in CUSTOM_STYLES) {
if (CUSTOM_STYLES[att].set) {
CUSTOM_STYLES[att].set(node, val, style);
return; // NOTE: return
} else if (typeof CUSTOM_STYLES[att] === 'string') {
att = CUSTOM_STYLES[att];
}
} else if (att === '') { // unset inline styles
att = 'cssText';
val = '';
}
style[att] = val;
}
},
/**
* Returns the current style value for the given property.
* @method getStyle
* @param {HTMLElement} An HTMLElement to get the style from.
* @param {String} att The style property to get.
*/
getStyle: function(node, att, style) {
style = style || node.style;
var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES,
val = '';
if (style) {
if (att in CUSTOM_STYLES) {
if (CUSTOM_STYLES[att].get) {
return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return
} else if (typeof CUSTOM_STYLES[att] === 'string') {
att = CUSTOM_STYLES[att];
}
}
val = style[att];
if (val === '') { // TODO: is empty string sufficient?
val = Y_DOM[GET_COMPUTED_STYLE](node, att);
}
}
return val;
},
/**
* Sets multiple style properties.
* @method setStyles
* @param {HTMLElement} node An HTMLElement to apply the styles to.
* @param {Object} hash An object literal of property:value pairs.
*/
setStyles: function(node, hash) {
var style = node.style;
Y.each(hash, function(v, n) {
Y_DOM.setStyle(node, n, v, style);
}, Y_DOM);
},
/**
* Returns the computed style for the given node.
* @method getComputedStyle
* @param {HTMLElement} An HTMLElement to get the style from.
* @param {String} att The style property to get.
* @return {String} The computed value of the style property.
*/
getComputedStyle: function(node, att) {
var val = '',
doc = node[OWNER_DOCUMENT],
computed;
if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) {
computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null);
if (computed) { // FF may be null in some cases (ticket #2530548)
val = computed[att];
}
}
return val;
}
});
// normalize reserved word float alternatives ("cssFloat" or "styleFloat")
if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) {
Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT;
} else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) {
Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT;
}
// fix opera computedStyle default color unit (convert to rgb)
if (Y.UA.opera) {
Y_DOM[GET_COMPUTED_STYLE] = function(node, att) {
var view = node[OWNER_DOCUMENT][DEFAULT_VIEW],
val = view[GET_COMPUTED_STYLE](node, '')[att];
if (re_color.test(att)) {
val = Y.Color.toRGB(val);
}
return val;
};
}
// safari converts transparent to rgba(), others use "transparent"
if (Y.UA.webkit) {
Y_DOM[GET_COMPUTED_STYLE] = function(node, att) {
var view = node[OWNER_DOCUMENT][DEFAULT_VIEW],
val = view[GET_COMPUTED_STYLE](node, '')[att];
if (val === 'rgba(0, 0, 0, 0)') {
val = TRANSPARENT;
}
return val;
};
}
Y.DOM._getAttrOffset = function(node, attr) {
var val = Y.DOM[GET_COMPUTED_STYLE](node, attr),
offsetParent = node.offsetParent,
position,
parentOffset,
offset;
if (val === 'auto') {
position = Y.DOM.getStyle(node, 'position');
if (position === 'static' || position === 'relative') {
val = 0;
} else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) {
parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr];
offset = node[GET_BOUNDING_CLIENT_RECT]()[attr];
if (attr === 'left' || attr === 'top') {
val = offset - parentOffset;
} else {
val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr];
}
}
}
return val;
};
Y.DOM._getOffset = function(node) {
var pos,
xy = null;
if (node) {
pos = Y_DOM.getStyle(node, 'position');
xy = [
parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10),
parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10)
];
if ( isNaN(xy[0]) ) { // in case of 'auto'
xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline
if ( isNaN(xy[0]) ) { // default to offset value
xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0;
}
}
if ( isNaN(xy[1]) ) { // in case of 'auto'
xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline
if ( isNaN(xy[1]) ) { // default to offset value
xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0;
}
}
}
return xy;
};
Y_DOM.CUSTOM_STYLES.transform = {
set: function(node, val, style) {
style[TRANSFORM] = val;
},
get: function(node, style) {
return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM);
}
};
})(Y);
(function(Y) {
var PARSE_INT = parseInt,
RE = RegExp;
Y.Color = {
KEYWORDS: {
black: '000',
silver: 'c0c0c0',
gray: '808080',
white: 'fff',
maroon: '800000',
red: 'f00',
purple: '800080',
fuchsia: 'f0f',
green: '008000',
lime: '0f0',
olive: '808000',
yellow: 'ff0',
navy: '000080',
blue: '00f',
teal: '008080',
aqua: '0ff'
},
re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,
re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,
re_hex3: /([0-9A-F])/gi,
toRGB: function(val) {
if (!Y.Color.re_RGB.test(val)) {
val = Y.Color.toHex(val);
}
if(Y.Color.re_hex.exec(val)) {
val = 'rgb(' + [
PARSE_INT(RE.$1, 16),
PARSE_INT(RE.$2, 16),
PARSE_INT(RE.$3, 16)
].join(', ') + ')';
}
return val;
},
toHex: function(val) {
val = Y.Color.KEYWORDS[val] || val;
if (Y.Color.re_RGB.exec(val)) {
val = [
Number(RE.$1).toString(16),
Number(RE.$2).toString(16),
Number(RE.$3).toString(16)
];
for (var i = 0; i < val.length; i++) {
if (val[i].length < 2) {
val[i] = '0' + val[i];
}
}
val = val.join('');
}
if (val.length < 6) {
val = val.replace(Y.Color.re_hex3, '$1$1');
}
if (val !== 'transparent' && val.indexOf('#') < 0) {
val = '#' + val;
}
return val.toUpperCase();
}
};
})(Y);
}, '@VERSION@' ,{requires:['dom-base']});
YUI.add('dom-style-ie', function(Y) {
(function(Y) {
var HAS_LAYOUT = 'hasLayout',
PX = 'px',
FILTER = 'filter',
FILTERS = 'filters',
OPACITY = 'opacity',
AUTO = 'auto',
BORDER_WIDTH = 'borderWidth',
BORDER_TOP_WIDTH = 'borderTopWidth',
BORDER_RIGHT_WIDTH = 'borderRightWidth',
BORDER_BOTTOM_WIDTH = 'borderBottomWidth',
BORDER_LEFT_WIDTH = 'borderLeftWidth',
WIDTH = 'width',
HEIGHT = 'height',
TRANSPARENT = 'transparent',
VISIBLE = 'visible',
GET_COMPUTED_STYLE = 'getComputedStyle',
UNDEFINED = undefined,
documentElement = Y.config.doc.documentElement,
testFeature = Y.Features.test,
addFeature = Y.Features.add,
// TODO: unit-less lineHeight (e.g. 1.22)
re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i,
isIE8 = (Y.UA.ie >= 8),
_getStyleObj = function(node) {
return node.currentStyle || node.style;
},
ComputedStyle = {
CUSTOM_STYLES: {},
get: function(el, property) {
var value = '',
current;
if (el) {
current = _getStyleObj(el)[property];
if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) {
value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el);
} else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert
value = current;
} else if (Y.DOM.IE.COMPUTED[property]) { // use compute function
value = Y.DOM.IE.COMPUTED[property](el, property);
} else if (re_unit.test(current)) { // convert to pixel
value = ComputedStyle.getPixel(el, property) + PX;
} else {
value = current;
}
}
return value;
},
sizeOffsets: {
width: ['Left', 'Right'],
height: ['Top', 'Bottom'],
top: ['Top'],
bottom: ['Bottom']
},
getOffset: function(el, prop) {
var current = _getStyleObj(el)[prop], // value of "width", "top", etc.
capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc.
offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc.
pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc.
sizeOffsets = ComputedStyle.sizeOffsets[prop],
mode = el.ownerDocument.compatMode,
value = '';
// IE pixelWidth incorrect for percent
// manually compute by subtracting padding and border from offset size
// NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used
// reverting to auto from auto causes position stacking issues (old impl)
if (current === AUTO || current.indexOf('%') > -1) {
value = el['offset' + capped];
if (mode !== 'BackCompat') {
if (sizeOffsets[0]) {
value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]);
value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1);
}
if (sizeOffsets[1]) {
value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]);
value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1);
}
}
} else { // use style.pixelWidth, etc. to convert to pixels
// need to map style.width to currentStyle (no currentStyle.pixelWidth)
if (!el.style[pixel] && !el.style[prop]) {
el.style[prop] = current;
}
value = el.style[pixel];
}
return value + PX;
},
borderMap: {
thin: (isIE8) ? '1px' : '2px',
medium: (isIE8) ? '3px': '4px',
thick: (isIE8) ? '5px' : '6px'
},
getBorderWidth: function(el, property, omitUnit) {
var unit = omitUnit ? '' : PX,
current = el.currentStyle[property];
if (current.indexOf(PX) < 0) { // look up keywords if a border exists
if (ComputedStyle.borderMap[current] &&
el.currentStyle.borderStyle !== 'none') {
current = ComputedStyle.borderMap[current];
} else { // otherwise no border (default is "medium")
current = 0;
}
}
return (omitUnit) ? parseFloat(current) : current;
},
getPixel: function(node, att) {
// use pixelRight to convert to px
var val = null,
style = _getStyleObj(node),
styleRight = style.right,
current = style[att];
node.style.right = current;
val = node.style.pixelRight;
node.style.right = styleRight; // revert
return val;
},
getMargin: function(node, att) {
var val,
style = _getStyleObj(node);
if (style[att] == AUTO) {
val = 0;
} else {
val = ComputedStyle.getPixel(node, att);
}
return val + PX;
},
getVisibility: function(node, att) {
var current;
while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test
node = node.parentNode;
}
return (current) ? current[att] : VISIBLE;
},
getColor: function(node, att) {
var current = _getStyleObj(node)[att];
if (!current || current === TRANSPARENT) {
Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) {
current = _getStyleObj(parent)[att];
if (current && current !== TRANSPARENT) {
node = parent;
return true;
}
});
}
return Y.Color.toRGB(current);
},
getBorderColor: function(node, att) {
var current = _getStyleObj(node),
val = current[att] || current.color;
return Y.Color.toRGB(Y.Color.toHex(val));
}
},
//fontSize: getPixelFont,
IEComputed = {};
addFeature('style', 'computedStyle', {
test: function() {
return 'getComputedStyle' in Y.config.win;
}
});
addFeature('style', 'opacity', {
test: function() {
return 'opacity' in documentElement.style;
}
});
addFeature('style', 'filter', {
test: function() {
return 'filters' in documentElement;
}
});
// use alpha filter for IE opacity
if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) {
Y.DOM.CUSTOM_STYLES[OPACITY] = {
get: function(node) {
var val = 100;
try { // will error if no DXImageTransform
val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY];
} catch(e) {
try { // make sure its in the document
val = node[FILTERS]('alpha')[OPACITY];
} catch(err) {
Y.log('getStyle: IE opacity filter not found; returning 1', 'warn', 'dom-style');
}
}
return val / 100;
},
set: function(node, val, style) {
var current,
styleObj = _getStyleObj(node),
currentFilter = styleObj[FILTER];
style = style || node.style;
if (val === '') { // normalize inline style behavior
current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity
val = current;
}
if (typeof currentFilter == 'string') { // in case not appended
style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') +
((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : '');
if (!style[FILTER]) {
style.removeAttribute(FILTER);
}
if (!styleObj[HAS_LAYOUT]) {
style.zoom = 1; // needs layout
}
}
}
};
}
try {
Y.config.doc.createElement('div').style.height = '-1px';
} catch(e) { // IE throws error on invalid style set; trap common cases
Y.DOM.CUSTOM_STYLES.height = {
set: function(node, val, style) {
var floatVal = parseFloat(val);
if (floatVal >= 0 || val === 'auto' || val === '') {
style.height = val;
} else {
Y.log('invalid style value for height: ' + val, 'warn', 'dom-style');
}
}
};
Y.DOM.CUSTOM_STYLES.width = {
set: function(node, val, style) {
var floatVal = parseFloat(val);
if (floatVal >= 0 || val === 'auto' || val === '') {
style.width = val;
} else {
Y.log('invalid style value for width: ' + val, 'warn', 'dom-style');
}
}
};
}
if (!testFeature('style', 'computedStyle')) {
// TODO: top, right, bottom, left
IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset;
IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor;
IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] =
IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] =
ComputedStyle.getBorderWidth;
IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom =
IEComputed.marginLeft = ComputedStyle.getMargin;
IEComputed.visibility = ComputedStyle.getVisibility;
IEComputed.borderColor = IEComputed.borderTopColor =
IEComputed.borderRightColor = IEComputed.borderBottomColor =
IEComputed.borderLeftColor = ComputedStyle.getBorderColor;
Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get;
Y.namespace('DOM.IE');
Y.DOM.IE.COMPUTED = IEComputed;
Y.DOM.IE.ComputedStyle = ComputedStyle;
}
})(Y);
}, '@VERSION@' ,{requires:['dom-style']});
YUI.add('dom-screen', function(Y) {
(function(Y) {
/**
* Adds position and region management functionality to DOM.
* @module dom
* @submodule dom-screen
* @for DOM
*/
var DOCUMENT_ELEMENT = 'documentElement',
COMPAT_MODE = 'compatMode',
POSITION = 'position',
FIXED = 'fixed',
RELATIVE = 'relative',
LEFT = 'left',
TOP = 'top',
_BACK_COMPAT = 'BackCompat',
MEDIUM = 'medium',
BORDER_LEFT_WIDTH = 'borderLeftWidth',
BORDER_TOP_WIDTH = 'borderTopWidth',
GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect',
GET_COMPUTED_STYLE = 'getComputedStyle',
Y_DOM = Y.DOM,
// TODO: how about thead/tbody/tfoot/tr?
// TODO: does caption matter?
RE_TABLE = /^t(?:able|d|h)$/i,
SCROLL_NODE;
if (Y.UA.ie) {
if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') {
SCROLL_NODE = DOCUMENT_ELEMENT;
} else {
SCROLL_NODE = 'body';
}
}
Y.mix(Y_DOM, {
/**
* Returns the inner height of the viewport (exludes scrollbar).
* @method winHeight
* @return {Number} The current height of the viewport.
*/
winHeight: function(node) {
var h = Y_DOM._getWinSize(node).height;
Y.log('winHeight returning ' + h, 'info', 'dom-screen');
return h;
},
/**
* Returns the inner width of the viewport (exludes scrollbar).
* @method winWidth
* @return {Number} The current width of the viewport.
*/
winWidth: function(node) {
var w = Y_DOM._getWinSize(node).width;
Y.log('winWidth returning ' + w, 'info', 'dom-screen');
return w;
},
/**
* Document height
* @method docHeight
* @return {Number} The current height of the document.
*/
docHeight: function(node) {
var h = Y_DOM._getDocSize(node).height;
Y.log('docHeight returning ' + h, 'info', 'dom-screen');
return Math.max(h, Y_DOM._getWinSize(node).height);
},
/**
* Document width
* @method docWidth
* @return {Number} The current width of the document.
*/
docWidth: function(node) {
var w = Y_DOM._getDocSize(node).width;
Y.log('docWidth returning ' + w, 'info', 'dom-screen');
return Math.max(w, Y_DOM._getWinSize(node).width);
},
/**
* Amount page has been scroll horizontally
* @method docScrollX
* @return {Number} The current amount the screen is scrolled horizontally.
*/
docScrollX: function(node, doc) {
doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization
var dv = doc.defaultView,
pageOffset = (dv) ? dv.pageXOffset : 0;
return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset);
},
/**
* Amount page has been scroll vertically
* @method docScrollY
* @return {Number} The current amount the screen is scrolled vertically.
*/
docScrollY: function(node, doc) {
doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization
var dv = doc.defaultView,
pageOffset = (dv) ? dv.pageYOffset : 0;
return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset);
},
/**
* Gets the current position of an element based on page coordinates.
* Element must be part of the DOM tree to have page coordinates
* (display:none or elements not appended return false).
* @method getXY
* @param element The target element
* @return {Array} The XY position of the element
TODO: test inDocument/display?
*/
getXY: function() {
if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) {
return function(node) {
var xy = null,
scrollLeft,
scrollTop,
mode,
box,
offX,
offY,
doc,
win,
inDoc,
rootNode;
if (node && node.tagName) {
doc = node.ownerDocument;
mode = doc[COMPAT_MODE];
if (mode !== _BACK_COMPAT) {
rootNode = doc[DOCUMENT_ELEMENT];
} else {
rootNode = doc.body;
}
// inline inDoc check for perf
if (rootNode.contains) {
inDoc = rootNode.contains(node);
} else {
inDoc = Y.DOM.contains(rootNode, node);
}
if (inDoc) {
win = doc.defaultView;
// inline scroll calc for perf
if (win && 'pageXOffset' in win) {
scrollLeft = win.pageXOffset;
scrollTop = win.pageYOffset;
} else {
scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc);
scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc);
}
if (Y.UA.ie) { // IE < 8, quirks, or compatMode
if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) {
offX = rootNode.clientLeft;
offY = rootNode.clientTop;
}
}
box = node[GET_BOUNDING_CLIENT_RECT]();
xy = [box.left, box.top];
if (offX || offY) {
xy[0] -= offX;
xy[1] -= offY;
}
if ((scrollTop || scrollLeft)) {
if (!Y.UA.ios || (Y.UA.ios >= 4.2)) {
xy[0] += scrollLeft;
xy[1] += scrollTop;
}
}
} else {
xy = Y_DOM._getOffset(node);
}
}
return xy;
};
} else {
return function(node) { // manually calculate by crawling up offsetParents
//Calculate the Top and Left border sizes (assumes pixels)
var xy = null,
doc,
parentNode,
bCheck,
scrollTop,
scrollLeft;
if (node) {
if (Y_DOM.inDoc(node)) {
xy = [node.offsetLeft, node.offsetTop];
doc = node.ownerDocument;
parentNode = node;
// TODO: refactor with !! or just falsey
bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false);
// TODO: worth refactoring for TOP/LEFT only?
while ((parentNode = parentNode.offsetParent)) {
xy[0] += parentNode.offsetLeft;
xy[1] += parentNode.offsetTop;
if (bCheck) {
xy = Y_DOM._calcBorders(parentNode, xy);
}
}
// account for any scrolled ancestors
if (Y_DOM.getStyle(node, POSITION) != FIXED) {
parentNode = node;
while ((parentNode = parentNode.parentNode)) {
scrollTop = parentNode.scrollTop;
scrollLeft = parentNode.scrollLeft;
//Firefox does something funky with borders when overflow is not visible.
if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) {
xy = Y_DOM._calcBorders(parentNode, xy);
}
if (scrollTop || scrollLeft) {
xy[0] -= scrollLeft;
xy[1] -= scrollTop;
}
}
xy[0] += Y_DOM.docScrollX(node, doc);
xy[1] += Y_DOM.docScrollY(node, doc);
} else {
//Fix FIXED position -- add scrollbars
xy[0] += Y_DOM.docScrollX(node, doc);
xy[1] += Y_DOM.docScrollY(node, doc);
}
} else {
xy = Y_DOM._getOffset(node);
}
}
return xy;
};
}
}(),// NOTE: Executing for loadtime branching
/**
Gets the width of vertical scrollbars on overflowed containers in the body
content.
@method getScrollbarWidth
@return {Number} Pixel width of a scrollbar in the current browser
**/
getScrollbarWidth: Y.cached(function () {
var doc = Y.config.doc,
testNode = doc.createElement('div'),
body = doc.getElementsByTagName('body')[0],
// 0.1 because cached doesn't support falsy refetch values
width = 0.1;
if (body) {
testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;";
testNode.appendChild(doc.createElement('p')).style.height = '1px';
body.insertBefore(testNode, body.firstChild);
width = testNode.offsetWidth - testNode.clientWidth;
body.removeChild(testNode);
}
return width;
}, null, 0.1),
/**
* Gets the current X position of an element based on page coordinates.
* Element must be part of the DOM tree to have page coordinates
* (display:none or elements not appended return false).
* @method getX
* @param element The target element
* @return {Number} The X position of the element
*/
getX: function(node) {
return Y_DOM.getXY(node)[0];
},
/**
* Gets the current Y position of an element based on page coordinates.
* Element must be part of the DOM tree to have page coordinates
* (display:none or elements not appended return false).
* @method getY
* @param element The target element
* @return {Number} The Y position of the element
*/
getY: function(node) {
return Y_DOM.getXY(node)[1];
},
/**
* Set the position of an html element in page coordinates.
* The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method setXY
* @param element The target element
* @param {Array} xy Contains X & Y values for new position (coordinates are page-based)
* @param {Boolean} noRetry By default we try and set the position a second time if the first fails
*/
setXY: function(node, xy, noRetry) {
var setStyle = Y_DOM.setStyle,
pos,
delta,
newXY,
currentXY;
if (node && xy) {
pos = Y_DOM.getStyle(node, POSITION);
delta = Y_DOM._getOffset(node);
if (pos == 'static') { // default to relative
pos = RELATIVE;
setStyle(node, POSITION, pos);
}
currentXY = Y_DOM.getXY(node);
if (xy[0] !== null) {
setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px');
}
if (xy[1] !== null) {
setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px');
}
if (!noRetry) {
newXY = Y_DOM.getXY(node);
if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) {
Y_DOM.setXY(node, xy, true);
}
}
Y.log('setXY setting position to ' + xy, 'info', 'dom-screen');
} else {
Y.log('setXY failed to set ' + node + ' to ' + xy, 'info', 'dom-screen');
}
},
/**
* Set the X position of an html element in page coordinates, regardless of how the element is positioned.
* The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method setX
* @param element The target element
* @param {Number} x The X values for new position (coordinates are page-based)
*/
setX: function(node, x) {
return Y_DOM.setXY(node, [x, null]);
},
/**
* Set the Y position of an html element in page coordinates, regardless of how the element is positioned.
* The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method setY
* @param element The target element
* @param {Number} y The Y values for new position (coordinates are page-based)
*/
setY: function(node, y) {
return Y_DOM.setXY(node, [null, y]);
},
/**
* @method swapXY
* @description Swap the xy position with another node
* @param {Node} node The node to swap with
* @param {Node} otherNode The other node to swap with
* @return {Node}
*/
swapXY: function(node, otherNode) {
var xy = Y_DOM.getXY(node);
Y_DOM.setXY(node, Y_DOM.getXY(otherNode));
Y_DOM.setXY(otherNode, xy);
},
_calcBorders: function(node, xy2) {
var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0,
l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0;
if (Y.UA.gecko) {
if (RE_TABLE.test(node.tagName)) {
t = 0;
l = 0;
}
}
xy2[0] += l;
xy2[1] += t;
return xy2;
},
_getWinSize: function(node, doc) {
doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc;
var win = doc.defaultView || doc.parentWindow,
mode = doc[COMPAT_MODE],
h = win.innerHeight,
w = win.innerWidth,
root = doc[DOCUMENT_ELEMENT];
if ( mode && !Y.UA.opera ) { // IE, Gecko
if (mode != 'CSS1Compat') { // Quirks
root = doc.body;
}
h = root.clientHeight;
w = root.clientWidth;
}
return { height: h, width: w };
},
_getDocSize: function(node) {
var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc,
root = doc[DOCUMENT_ELEMENT];
if (doc[COMPAT_MODE] != 'CSS1Compat') {
root = doc.body;
}
return { height: root.scrollHeight, width: root.scrollWidth };
}
});
})(Y);
(function(Y) {
var TOP = 'top',
RIGHT = 'right',
BOTTOM = 'bottom',
LEFT = 'left',
getOffsets = function(r1, r2) {
var t = Math.max(r1[TOP], r2[TOP]),
r = Math.min(r1[RIGHT], r2[RIGHT]),
b = Math.min(r1[BOTTOM], r2[BOTTOM]),
l = Math.max(r1[LEFT], r2[LEFT]),
ret = {};
ret[TOP] = t;
ret[RIGHT] = r;
ret[BOTTOM] = b;
ret[LEFT] = l;
return ret;
},
DOM = Y.DOM;
Y.mix(DOM, {
/**
* Returns an Object literal containing the following about this element: (top, right, bottom, left)
* @for DOM
* @method region
* @param {HTMLElement} element The DOM element.
* @return {Object} Object literal containing the following about this element: (top, right, bottom, left)
*/
region: function(node) {
var xy = DOM.getXY(node),
ret = false;
if (node && xy) {
ret = DOM._getRegion(
xy[1], // top
xy[0] + node.offsetWidth, // right
xy[1] + node.offsetHeight, // bottom
xy[0] // left
);
}
return ret;
},
/**
* Find the intersect information for the passed nodes.
* @method intersect
* @for DOM
* @param {HTMLElement} element The first element
* @param {HTMLElement | Object} element2 The element or region to check the interect with
* @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop)
* @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion)
*/
intersect: function(node, node2, altRegion) {
var r = altRegion || DOM.region(node), region = {},
n = node2,
off;
if (n.tagName) {
region = DOM.region(n);
} else if (Y.Lang.isObject(node2)) {
region = node2;
} else {
return false;
}
off = getOffsets(region, r);
return {
top: off[TOP],
right: off[RIGHT],
bottom: off[BOTTOM],
left: off[LEFT],
area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])),
yoff: ((off[BOTTOM] - off[TOP])),
xoff: (off[RIGHT] - off[LEFT]),
inRegion: DOM.inRegion(node, node2, false, altRegion)
};
},
/**
* Check if any part of this node is in the passed region
* @method inRegion
* @for DOM
* @param {Object} node The node to get the region from
* @param {Object} node2 The second node to get the region from or an Object literal of the region
* @param {Boolean} all Should all of the node be inside the region
* @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop)
* @return {Boolean} True if in region, false if not.
*/
inRegion: function(node, node2, all, altRegion) {
var region = {},
r = altRegion || DOM.region(node),
n = node2,
off;
if (n.tagName) {
region = DOM.region(n);
} else if (Y.Lang.isObject(node2)) {
region = node2;
} else {
return false;
}
if (all) {
return (
r[LEFT] >= region[LEFT] &&
r[RIGHT] <= region[RIGHT] &&
r[TOP] >= region[TOP] &&
r[BOTTOM] <= region[BOTTOM] );
} else {
off = getOffsets(region, r);
if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) {
return true;
} else {
return false;
}
}
},
/**
* Check if any part of this element is in the viewport
* @method inViewportRegion
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {Boolean} all Should all of the node be inside the region
* @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop)
* @return {Boolean} True if in region, false if not.
*/
inViewportRegion: function(node, all, altRegion) {
return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion);
},
_getRegion: function(t, r, b, l) {
var region = {};
region[TOP] = region[1] = t;
region[LEFT] = region[0] = l;
region[BOTTOM] = b;
region[RIGHT] = r;
region.width = region[RIGHT] - region[LEFT];
region.height = region[BOTTOM] - region[TOP];
return region;
},
/**
* Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left)
* @method viewportRegion
* @for DOM
* @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left)
*/
viewportRegion: function(node) {
node = node || Y.config.doc.documentElement;
var ret = false,
scrollX,
scrollY;
if (node) {
scrollX = DOM.docScrollX(node);
scrollY = DOM.docScrollY(node);
ret = DOM._getRegion(scrollY, // top
DOM.winWidth(node) + scrollX, // right
scrollY + DOM.winHeight(node), // bottom
scrollX); // left
}
return ret;
}
});
})(Y);
}, '@VERSION@' ,{requires:['dom-base', 'dom-style']});
YUI.add('selector-native', function(Y) {
(function(Y) {
/**
* The selector-native module provides support for native querySelector
* @module dom
* @submodule selector-native
* @for Selector
*/
/**
* Provides support for using CSS selectors to query the DOM
* @class Selector
* @static
* @for Selector
*/
Y.namespace('Selector'); // allow native module to standalone
var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition',
OWNER_DOCUMENT = 'ownerDocument';
var Selector = {
_types: {
esc: {
token: '\uE000',
re: /\\[:\[\]\(\)#\.\'\>+~"]/gi
},
attr: {
token: '\uE001',
re: /(\[[^\]]*\])/g
},
pseudo: {
token: '\uE002',
re: /(\([^\)]*\))/g
}
},
useNative: true,
_escapeId: function(id) {
if (id) {
id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1');
}
return id;
},
_compare: ('sourceIndex' in Y.config.doc.documentElement) ?
function(nodeA, nodeB) {
var a = nodeA.sourceIndex,
b = nodeB.sourceIndex;
if (a === b) {
return 0;
} else if (a > b) {
return 1;
}
return -1;
} : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ?
function(nodeA, nodeB) {
if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) {
return -1;
} else {
return 1;
}
} :
function(nodeA, nodeB) {
var rangeA, rangeB, compare;
if (nodeA && nodeB) {
rangeA = nodeA[OWNER_DOCUMENT].createRange();
rangeA.setStart(nodeA, 0);
rangeB = nodeB[OWNER_DOCUMENT].createRange();
rangeB.setStart(nodeB, 0);
compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END
}
return compare;
}),
_sort: function(nodes) {
if (nodes) {
nodes = Y.Array(nodes, 0, true);
if (nodes.sort) {
nodes.sort(Selector._compare);
}
}
return nodes;
},
_deDupe: function(nodes) {
var ret = [],
i, node;
for (i = 0; (node = nodes[i++]);) {
if (!node._found) {
ret[ret.length] = node;
node._found = true;
}
}
for (i = 0; (node = ret[i++]);) {
node._found = null;
node.removeAttribute('_found');
}
return ret;
},
/**
* Retrieves a set of nodes based on a given CSS selector.
* @method query
*
* @param {string} selector The CSS Selector to test the node against.
* @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc
* @param {Boolean} firstOnly optional Whether or not to return only the first match.
* @return {Array} An array of nodes that match the given selector.
* @static
*/
query: function(selector, root, firstOnly, skipNative) {
root = root || Y.config.doc;
var ret = [],
useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative),
queries = [[selector, root]],
query,
result,
i,
fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery;
if (selector && fn) {
// split group into seperate queries
if (!skipNative && // already done if skipping
(!useNative || root.tagName)) { // split native when element scoping is needed
queries = Selector._splitQueries(selector, root);
}
for (i = 0; (query = queries[i++]);) {
result = fn(query[0], query[1], firstOnly);
if (!firstOnly) { // coerce DOM Collection to Array
result = Y.Array(result, 0, true);
}
if (result) {
ret = ret.concat(result);
}
}
if (queries.length > 1) { // remove dupes and sort by doc order
ret = Selector._sort(Selector._deDupe(ret));
}
}
Y.log('query: ' + selector + ' returning: ' + ret.length, 'info', 'Selector');
return (firstOnly) ? (ret[0] || null) : ret;
},
_replaceSelector: function(selector) {
var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc.
attrs,
pseudos;
// first replace escaped chars, which could be present in attrs or pseudos
selector = Y.Selector._replace('esc', selector);
// then replace pseudos before attrs to avoid replacing :not([foo])
pseudos = Y.Selector._parse('pseudo', selector);
selector = Selector._replace('pseudo', selector);
attrs = Y.Selector._parse('attr', selector);
selector = Y.Selector._replace('attr', selector);
return {
esc: esc,
attrs: attrs,
pseudos: pseudos,
selector: selector
}
},
_restoreSelector: function(replaced) {
var selector = replaced.selector;
selector = Y.Selector._restore('attr', selector, replaced.attrs);
selector = Y.Selector._restore('pseudo', selector, replaced.pseudos);
selector = Y.Selector._restore('esc', selector, replaced.esc);
return selector;
},
_replaceCommas: function(selector) {
var replaced = Y.Selector._replaceSelector(selector),
selector = replaced.selector;
if (selector) {
selector = selector.replace(',', '\uE007', 'g');
replaced.selector = selector;
selector = Y.Selector._restoreSelector(replaced);
}
return selector;
},
// allows element scoped queries to begin with combinator
// e.g. query('> p', document.body) === query('body > p')
_splitQueries: function(selector, node) {
if (selector.indexOf(',') > -1) {
selector = Y.Selector._replaceCommas(selector);
}
var groups = selector.split('\uE007'), // split on replaced comma token
queries = [],
prefix = '',
id,
i,
len;
if (node) {
// enforce for element scoping
if (node.nodeType === 1) { // Elements only
id = Y.Selector._escapeId(Y.DOM.getId(node));
if (!id) {
id = Y.guid();
Y.DOM.setId(node, id);
}
prefix = '[id="' + id + '"] ';
}
for (i = 0, len = groups.length; i < len; ++i) {
selector = prefix + groups[i];
queries.push([selector, node]);
}
}
return queries;
},
_nativeQuery: function(selector, root, one) {
if (Y.UA.webkit && selector.indexOf(':checked') > -1 &&
(Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked"
return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query
}
try {
//Y.log('trying native query with: ' + selector, 'info', 'selector-native');
return root['querySelector' + (one ? '' : 'All')](selector);
} catch(e) { // fallback to brute if available
//Y.log('native query error; reverting to brute query with: ' + selector, 'info', 'selector-native');
return Y.Selector.query(selector, root, one, true); // redo with skipNative true
}
},
filter: function(nodes, selector) {
var ret = [],
i, node;
if (nodes && selector) {
for (i = 0; (node = nodes[i++]);) {
if (Y.Selector.test(node, selector)) {
ret[ret.length] = node;
}
}
} else {
Y.log('invalid filter input (nodes: ' + nodes +
', selector: ' + selector + ')', 'warn', 'Selector');
}
return ret;
},
test: function(node, selector, root) {
var ret = false,
useFrag = false,
groups,
parent,
item,
items,
frag,
id,
i, j, group;
if (node && node.tagName) { // only test HTMLElements
if (typeof selector == 'function') { // test with function
ret = selector.call(node, node);
} else { // test with query
// we need a root if off-doc
groups = selector.split(',');
if (!root && !Y.DOM.inDoc(node)) {
parent = node.parentNode;
if (parent) {
root = parent;
} else { // only use frag when no parent to query
frag = node[OWNER_DOCUMENT].createDocumentFragment();
frag.appendChild(node);
root = frag;
useFrag = true;
}
}
root = root || node[OWNER_DOCUMENT];
id = Y.Selector._escapeId(Y.DOM.getId(node));
if (!id) {
id = Y.guid();
Y.DOM.setId(node, id);
}
for (i = 0; (group = groups[i++]);) { // TODO: off-dom test
group += '[id="' + id + '"]';
items = Y.Selector.query(group, root);
for (j = 0; item = items[j++];) {
if (item === node) {
ret = true;
break;
}
}
if (ret) {
break;
}
}
if (useFrag) { // cleanup
frag.removeChild(node);
}
};
}
return ret;
},
/**
* A convenience function to emulate Y.Node's aNode.ancestor(selector).
* @param {HTMLElement} element An HTMLElement to start the query from.
* @param {String} selector The CSS selector to test the node against.
* @return {HTMLElement} The ancestor node matching the selector, or null.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* @static
* @method ancestor
*/
ancestor: function (element, selector, testSelf) {
return Y.DOM.ancestor(element, function(n) {
return Y.Selector.test(n, selector);
}, testSelf);
},
_parse: function(name, selector) {
return selector.match(Y.Selector._types[name].re);
},
_replace: function(name, selector) {
var o = Y.Selector._types[name];
return selector.replace(o.re, o.token);
},
_restore: function(name, selector, items) {
if (items) {
var token = Y.Selector._types[name].token,
i, len;
for (i = 0, len = items.length; i < len; ++i) {
selector = selector.replace(token, items[i]);
}
}
return selector;
}
};
Y.mix(Y.Selector, Selector, true);
})(Y);
}, '@VERSION@' ,{requires:['dom-base']});
YUI.add('selector', function(Y) {
}, '@VERSION@' ,{requires:['selector-native']});
YUI.add('event-custom-base', function(Y) {
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
*/
Y.Env.evt = {
handles: {},
plugins: {}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* Allows for the insertion of methods that are executed before or after
* a specified method
* @class Do
* @static
*/
var DO_BEFORE = 0,
DO_AFTER = 1,
DO = {
/**
* Cache of objects touched by the utility
* @property objs
* @static
*/
objs: {},
/**
* <p>Execute the supplied method before the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:</p>
* <dl>
* <dt></code>Y.Do.Halt(message, returnValue)</code></dt>
* <dd>Immediatly stop execution and return
* <code>returnValue</code>. No other wrapping functions will be
* executed.</dd>
* <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt>
* <dd>Replace the arguments that the original function will be
* called with.</dd>
* <dt></code>Y.Do.Prevent(message)</code></dt>
* <dd>Don't execute the wrapped function. Other before phase
* wrappers will be executed.</dd>
* </dl>
*
* @method before
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {string} handle for the subscription
* @static
*/
before: function(fn, obj, sFn, c) {
// Y.log('Do before: ' + sFn, 'info', 'event');
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(DO_BEFORE, f, obj, sFn);
},
/**
* <p>Execute the supplied method after the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:</p>
* <dl>
* <dt></code>Y.Do.Halt(message, returnValue)</code></dt>
* <dd>Immediatly stop execution and return
* <code>returnValue</code>. No other wrapping functions will be
* executed.</dd>
* <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt>
* <dd>Return <code>returnValue</code> instead of the wrapped
* method's original return value. This can be further altered by
* other after phase wrappers.</dd>
* </dl>
*
* <p>The static properties <code>Y.Do.originalRetVal</code> and
* <code>Y.Do.currentRetVal</code> will be populated for reference.</p>
*
* @method after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return {string} handle for the subscription
* @static
*/
after: function(fn, obj, sFn, c) {
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(DO_AFTER, f, obj, sFn);
},
/**
* Execute the supplied method before or after the specified function.
* Used by <code>before</code> and <code>after</code>.
*
* @method _inject
* @param when {string} before or after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @return {string} handle for the subscription
* @private
* @static
*/
_inject: function(when, fn, obj, sFn) {
// object id
var id = Y.stamp(obj), o, sid;
if (! this.objs[id]) {
// create a map entry for the obj if it doesn't exist
this.objs[id] = {};
}
o = this.objs[id];
if (! o[sFn]) {
// create a map entry for the method if it doesn't exist
o[sFn] = new Y.Do.Method(obj, sFn);
// re-route the method to our wrapper
obj[sFn] =
function() {
return o[sFn].exec.apply(o[sFn], arguments);
};
}
// subscriber id
sid = id + Y.stamp(fn) + sFn;
// register the callback
o[sFn].register(sid, fn, when);
return new Y.EventHandle(o[sFn], sid);
},
/**
* Detach a before or after subscription.
*
* @method detach
* @param handle {string} the subscription handle
* @static
*/
detach: function(handle) {
if (handle.detach) {
handle.detach();
}
},
_unload: function(e, me) {
}
};
Y.Do = DO;
//////////////////////////////////////////////////////////////////////////
/**
* Contains the return value from the wrapped method, accessible
* by 'after' event listeners.
*
* @property originalRetVal
* @static
* @since 3.2.0
*/
/**
* Contains the current state of the return value, consumable by
* 'after' event listeners, and updated if an after subscriber
* changes the return value generated by the wrapped function.
*
* @property currentRetVal
* @static
* @since 3.2.0
*/
//////////////////////////////////////////////////////////////////////////
/**
* Wrapper for a displaced method with aop enabled
* @class Do.Method
* @constructor
* @param obj The object to operate on
* @param sFn The name of the method to displace
*/
DO.Method = function(obj, sFn) {
this.obj = obj;
this.methodName = sFn;
this.method = obj[sFn];
this.before = {};
this.after = {};
};
/**
* Register a aop subscriber
* @method register
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
DO.Method.prototype.register = function (sid, fn, when) {
if (when) {
this.after[sid] = fn;
} else {
this.before[sid] = fn;
}
};
/**
* Unregister a aop subscriber
* @method delete
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
DO.Method.prototype._delete = function (sid) {
// Y.log('Y.Do._delete: ' + sid, 'info', 'Event');
delete this.before[sid];
delete this.after[sid];
};
/**
* <p>Execute the wrapped method. All arguments are passed into the wrapping
* functions. If any of the before wrappers return an instance of
* <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped
* function nor any after phase subscribers will be executed.</p>
*
* <p>The return value will be the return value of the wrapped function or one
* provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or
* <code>Y.Do.AlterReturn</code>.
*
* @method exec
* @param arg* {any} Arguments are passed to the wrapping and wrapped functions
* @return {any} Return value of wrapped function unless overwritten (see above)
*/
DO.Method.prototype.exec = function () {
var args = Y.Array(arguments, 0, true),
i, ret, newRet,
bf = this.before,
af = this.after,
prevented = false;
// execute before
for (i in bf) {
if (bf.hasOwnProperty(i)) {
ret = bf[i].apply(this.obj, args);
if (ret) {
switch (ret.constructor) {
case DO.Halt:
return ret.retVal;
case DO.AlterArgs:
args = ret.newArgs;
break;
case DO.Prevent:
prevented = true;
break;
default:
}
}
}
}
// execute method
if (!prevented) {
ret = this.method.apply(this.obj, args);
}
DO.originalRetVal = ret;
DO.currentRetVal = ret;
// execute after methods.
for (i in af) {
if (af.hasOwnProperty(i)) {
newRet = af[i].apply(this.obj, args);
// Stop processing if a Halt object is returned
if (newRet && newRet.constructor == DO.Halt) {
return newRet.retVal;
// Check for a new return value
} else if (newRet && newRet.constructor == DO.AlterReturn) {
ret = newRet.newRetVal;
// Update the static retval state
DO.currentRetVal = ret;
}
}
}
return ret;
};
//////////////////////////////////////////////////////////////////////////
/**
* Return an AlterArgs object when you want to change the arguments that
* were passed into the function. Useful for Do.before subscribers. An
* example would be a service that scrubs out illegal characters prior to
* executing the core business logic.
* @class Do.AlterArgs
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param newArgs {Array} Call parameters to be used for the original method
* instead of the arguments originally passed in.
*/
DO.AlterArgs = function(msg, newArgs) {
this.msg = msg;
this.newArgs = newArgs;
};
/**
* Return an AlterReturn object when you want to change the result returned
* from the core method to the caller. Useful for Do.after subscribers.
* @class Do.AlterReturn
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param newRetVal {any} Return value passed to code that invoked the wrapped
* function.
*/
DO.AlterReturn = function(msg, newRetVal) {
this.msg = msg;
this.newRetVal = newRetVal;
};
/**
* Return a Halt object when you want to terminate the execution
* of all subsequent subscribers as well as the wrapped method
* if it has not exectued yet. Useful for Do.before subscribers.
* @class Do.Halt
* @constructor
* @param msg {String} (optional) Explanation of why the termination was done
* @param retVal {any} Return value passed to code that invoked the wrapped
* function.
*/
DO.Halt = function(msg, retVal) {
this.msg = msg;
this.retVal = retVal;
};
/**
* Return a Prevent object when you want to prevent the wrapped function
* from executing, but want the remaining listeners to execute. Useful
* for Do.before subscribers.
* @class Do.Prevent
* @constructor
* @param msg {String} (optional) Explanation of why the termination was done
*/
DO.Prevent = function(msg) {
this.msg = msg;
};
/**
* Return an Error object when you want to terminate the execution
* of all subsequent method calls.
* @class Do.Error
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param retVal {any} Return value passed to code that invoked the wrapped
* function.
* @deprecated use Y.Do.Halt or Y.Do.Prevent
*/
DO.Error = DO.Halt;
//////////////////////////////////////////////////////////////////////////
// Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do);
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
// var onsubscribeType = "_event:onsub",
var AFTER = 'after',
CONFIGS = [
'broadcast',
'monitored',
'bubbles',
'context',
'contextFn',
'currentTarget',
'defaultFn',
'defaultTargetOnly',
'details',
'emitFacade',
'fireOnce',
'async',
'host',
'preventable',
'preventedFn',
'queuable',
'silent',
'stoppedFn',
'target',
'type'
],
YUI3_SIGNATURE = 9,
YUI_LOG = 'yui:log';
/**
* The CustomEvent class lets you define events for your application
* that can be subscribed to by one or more independent component.
*
* @param {String} type The type of event, which is passed to the callback
* when the event fires.
* @param {object} o configuration object.
* @class CustomEvent
* @constructor
*/
Y.CustomEvent = function(type, o) {
// if (arguments.length > 2) {
// this.log('CustomEvent context and silent are now in the config', 'warn', 'Event');
// }
o = o || {};
this.id = Y.stamp(this);
/**
* The type of event, returned to subscribers when the event fires
* @property type
* @type string
*/
this.type = type;
/**
* The context the the event will fire from by default. Defaults to the YUI
* instance.
* @property context
* @type object
*/
this.context = Y;
/**
* Monitor when an event is attached or detached.
*
* @property monitored
* @type boolean
*/
// this.monitored = false;
this.logSystem = (type == YUI_LOG);
/**
* If 0, this event does not broadcast. If 1, the YUI instance is notified
* every time this event fires. If 2, the YUI instance and the YUI global
* (if event is enabled on the global) are notified every time this event
* fires.
* @property broadcast
* @type int
*/
// this.broadcast = 0;
/**
* By default all custom events are logged in the debug build, set silent
* to true to disable debug outpu for this event.
* @property silent
* @type boolean
*/
this.silent = this.logSystem;
/**
* Specifies whether this event should be queued when the host is actively
* processing an event. This will effect exectution order of the callbacks
* for the various events.
* @property queuable
* @type boolean
* @default false
*/
// this.queuable = false;
/**
* The subscribers to this event
* @property subscribers
* @type Subscriber {}
*/
this.subscribers = {};
/**
* 'After' subscribers
* @property afters
* @type Subscriber {}
*/
this.afters = {};
/**
* This event has fired if true
*
* @property fired
* @type boolean
* @default false;
*/
// this.fired = false;
/**
* An array containing the arguments the custom event
* was last fired with.
* @property firedWith
* @type Array
*/
// this.firedWith;
/**
* This event should only fire one time if true, and if
* it has fired, any new subscribers should be notified
* immediately.
*
* @property fireOnce
* @type boolean
* @default false;
*/
// this.fireOnce = false;
/**
* fireOnce listeners will fire syncronously unless async
* is set to true
* @property async
* @type boolean
* @default false
*/
//this.async = false;
/**
* Flag for stopPropagation that is modified during fire()
* 1 means to stop propagation to bubble targets. 2 means
* to also stop additional subscribers on this target.
* @property stopped
* @type int
*/
// this.stopped = 0;
/**
* Flag for preventDefault that is modified during fire().
* if it is not 0, the default behavior for this event
* @property prevented
* @type int
*/
// this.prevented = 0;
/**
* Specifies the host for this custom event. This is used
* to enable event bubbling
* @property host
* @type EventTarget
*/
// this.host = null;
/**
* The default function to execute after event listeners
* have fire, but only if the default action was not
* prevented.
* @property defaultFn
* @type Function
*/
// this.defaultFn = null;
/**
* The function to execute if a subscriber calls
* stopPropagation or stopImmediatePropagation
* @property stoppedFn
* @type Function
*/
// this.stoppedFn = null;
/**
* The function to execute if a subscriber calls
* preventDefault
* @property preventedFn
* @type Function
*/
// this.preventedFn = null;
/**
* Specifies whether or not this event's default function
* can be cancelled by a subscriber by executing preventDefault()
* on the event facade
* @property preventable
* @type boolean
* @default true
*/
this.preventable = true;
/**
* Specifies whether or not a subscriber can stop the event propagation
* via stopPropagation(), stopImmediatePropagation(), or halt()
*
* Events can only bubble if emitFacade is true.
*
* @property bubbles
* @type boolean
* @default true
*/
this.bubbles = true;
/**
* Supports multiple options for listener signatures in order to
* port YUI 2 apps.
* @property signature
* @type int
* @default 9
*/
this.signature = YUI3_SIGNATURE;
this.subCount = 0;
this.afterCount = 0;
// this.hasSubscribers = false;
// this.hasAfters = false;
/**
* If set to true, the custom event will deliver an EventFacade object
* that is similar to a DOM event object.
* @property emitFacade
* @type boolean
* @default false
*/
// this.emitFacade = false;
this.applyConfig(o, true);
// this.log("Creating " + this.type);
};
Y.CustomEvent.prototype = {
constructor: Y.CustomEvent,
/**
* Returns the number of subscribers for this event as the sum of the on()
* subscribers and after() subscribers.
*
* @method hasSubs
* @return Number
*/
hasSubs: function(when) {
var s = this.subCount, a = this.afterCount, sib = this.sibling;
if (sib) {
s += sib.subCount;
a += sib.afterCount;
}
if (when) {
return (when == 'after') ? a : s;
}
return (s + a);
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('detach', 'attach', 'publish').
* @return {EventHandle} return value from the monitor event subscription.
*/
monitor: function(what) {
this.monitored = true;
var type = this.id + '|' + this.type + '_' + what,
args = Y.Array(arguments, 0, true);
args[0] = type;
return this.host.on.apply(this.host, args);
},
/**
* Get all of the subscribers to this event and any sibling event
* @method getSubs
* @return {Array} first item is the on subscribers, second the after.
*/
getSubs: function() {
var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling;
if (sib) {
Y.mix(s, sib.subscribers);
Y.mix(a, sib.afters);
}
return [s, a];
},
/**
* Apply configuration properties. Only applies the CONFIG whitelist
* @method applyConfig
* @param o hash of properties to apply.
* @param force {boolean} if true, properties that exist on the event
* will be overwritten.
*/
applyConfig: function(o, force) {
if (o) {
Y.mix(this, o, force, CONFIGS);
}
},
/**
* Create the Subscription for subscribing function, context, and bound
* arguments. If this is a fireOnce event, the subscriber is immediately
* notified.
*
* @method _on
* @param fn {Function} Subscription callback
* @param [context] {Object} Override `this` in the callback
* @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire()
* @param [when] {String} "after" to slot into after subscribers
* @return {EventHandle}
* @protected
*/
_on: function(fn, context, args, when) {
if (!fn) {
this.log('Invalid callback for CE: ' + this.type);
}
var s = new Y.Subscriber(fn, context, args, when);
if (this.fireOnce && this.fired) {
if (this.async) {
setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0);
} else {
this._notify(s, this.firedWith);
}
}
if (when == AFTER) {
this.afters[s.id] = s;
this.afterCount++;
} else {
this.subscribers[s.id] = s;
this.subCount++;
}
return new Y.EventHandle(this, s);
},
/**
* Listen for this event
* @method subscribe
* @param {Function} fn The function to execute.
* @return {EventHandle} Unsubscribe handle.
* @deprecated use on.
*/
subscribe: function(fn, context) {
Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated');
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null;
return this._on(fn, context, a, true);
},
/**
* Listen for this event
* @method on
* @param {Function} fn The function to execute.
* @param {object} context optional execution context.
* @param {mixed} arg* 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} An object with a detach method to detch the handler(s).
*/
on: function(fn, context) {
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null;
if (this.host) {
this.host._monitor('attach', this.type, {
args: arguments
});
}
return this._on(fn, context, a, true);
},
/**
* Listen for this event after the normal subscribers have been notified and
* the default behavior has been applied. If a normal subscriber prevents the
* default behavior, it also prevents after listeners from firing.
* @method after
* @param {Function} fn The function to execute.
* @param {object} context optional execution context.
* @param {mixed} arg* 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} handle Unsubscribe handle.
*/
after: function(fn, context) {
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null;
return this._on(fn, context, a, AFTER);
},
/**
* Detach listeners.
* @method detach
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed.
* @param {Object} context The context object passed to subscribe.
* @return {int} returns the number of subscribers unsubscribed.
*/
detach: function(fn, context) {
// unsubscribe handle
if (fn && fn.detach) {
return fn.detach();
}
var i, s,
found = 0,
subs = Y.merge(this.subscribers, this.afters);
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
if (s && (!fn || fn === s.fn)) {
this._delete(s);
found++;
}
}
}
return found;
},
/**
* Detach listeners.
* @method unsubscribe
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed.
* @param {Object} context The context object passed to subscribe.
* @return {int|undefined} returns the number of subscribers unsubscribed.
* @deprecated use detach.
*/
unsubscribe: function() {
return this.detach.apply(this, arguments);
},
/**
* Notify a single subscriber
* @method _notify
* @param {Subscriber} s the subscriber.
* @param {Array} args the arguments array to apply to the listener.
* @protected
*/
_notify: function(s, args, ef) {
this.log(this.type + '->' + 'sub: ' + s.id);
var ret;
ret = s.notify(args, this);
if (false === ret || this.stopped > 1) {
this.log(this.type + ' cancelled by subscriber');
return false;
}
return true;
},
/**
* Logger abstraction to centralize the application of the silent flag
* @method log
* @param {string} msg message to log.
* @param {string} cat log category.
*/
log: function(msg, cat) {
if (!this.silent) {
Y.log(this.id + ': ' + msg, cat || 'info', 'event');
}
},
/**
* Notifies the subscribers. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters:
* <ul>
* <li>The type of event</li>
* <li>All of the arguments fire() was executed with as an array</li>
* <li>The custom object (if any) that was passed into the subscribe()
* method</li>
* </ul>
* @method fire
* @param {Object*} arguments an arbitrary set of parameters to pass to
* the handler.
* @return {boolean} false if one of the subscribers returned false,
* true otherwise.
*
*/
fire: function() {
if (this.fireOnce && this.fired) {
this.log('fireOnce event: ' + this.type + ' already fired');
return true;
} else {
var args = Y.Array(arguments, 0, true);
// this doesn't happen if the event isn't published
// this.host._monitor('fire', this.type, args);
this.fired = true;
this.firedWith = args;
if (this.emitFacade) {
return this.fireComplex(args);
} else {
return this.fireSimple(args);
}
}
},
/**
* Set up for notifying subscribers of non-emitFacade events.
*
* @method fireSimple
* @param args {Array} Arguments passed to fire()
* @return Boolean false if a subscriber returned false
* @protected
*/
fireSimple: function(args) {
this.stopped = 0;
this.prevented = 0;
if (this.hasSubs()) {
// this._procSubs(Y.merge(this.subscribers, this.afters), args);
var subs = this.getSubs();
this._procSubs(subs[0], args);
this._procSubs(subs[1], args);
}
this._broadcast(args);
return this.stopped ? false : true;
},
// Requires the event-custom-complex module for full funcitonality.
fireComplex: function(args) {
Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type);
args[0] = args[0] || {};
return this.fireSimple(args);
},
/**
* Notifies a list of subscribers.
*
* @method _procSubs
* @param subs {Array} List of subscribers
* @param args {Array} Arguments passed to fire()
* @param ef {}
* @return Boolean false if a subscriber returns false or stops the event
* propagation via e.stopPropagation(),
* e.stopImmediatePropagation(), or e.halt()
* @private
*/
_procSubs: function(subs, args, ef) {
var s, i;
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
if (s && s.fn) {
if (false === this._notify(s, args, ef)) {
this.stopped = 2;
}
if (this.stopped == 2) {
return false;
}
}
}
}
return true;
},
/**
* Notifies the YUI instance if the event is configured with broadcast = 1,
* and both the YUI instance and Y.Global if configured with broadcast = 2.
*
* @method _broadcast
* @param args {Array} Arguments sent to fire()
* @private
*/
_broadcast: function(args) {
if (!this.stopped && this.broadcast) {
var a = Y.Array(args);
a.unshift(this.type);
if (this.host !== Y) {
Y.fire.apply(Y, a);
}
if (this.broadcast == 2) {
Y.Global.fire.apply(Y.Global, a);
}
}
},
/**
* Removes all listeners
* @method unsubscribeAll
* @return {int} The number of listeners unsubscribed.
* @deprecated use detachAll.
*/
unsubscribeAll: function() {
return this.detachAll.apply(this, arguments);
},
/**
* Removes all listeners
* @method detachAll
* @return {int} The number of listeners unsubscribed.
*/
detachAll: function() {
return this.detach();
},
/**
* Deletes the subscriber from the internal store of on() and after()
* subscribers.
*
* @method _delete
* @param subscriber object.
* @private
*/
_delete: function(s) {
if (s) {
if (this.subscribers[s.id]) {
delete this.subscribers[s.id];
this.subCount--;
}
if (this.afters[s.id]) {
delete this.afters[s.id];
this.afterCount--;
}
}
if (this.host) {
this.host._monitor('detach', this.type, {
ce: this,
sub: s
});
}
if (s) {
// delete s.fn;
// delete s.context;
s.deleted = true;
}
}
};
/**
* Stores the subscriber information to be used when the event fires.
* @param {Function} fn The wrapped function to execute.
* @param {Object} context The value of the keyword 'this' in the listener.
* @param {Array} args* 0..n additional arguments to supply the listener.
*
* @class Subscriber
* @constructor
*/
Y.Subscriber = function(fn, context, args) {
/**
* The callback that will be execute when the event fires
* This is wrapped by Y.rbind if obj was supplied.
* @property fn
* @type Function
*/
this.fn = fn;
/**
* Optional 'this' keyword for the listener
* @property context
* @type Object
*/
this.context = context;
/**
* Unique subscriber id
* @property id
* @type String
*/
this.id = Y.stamp(this);
/**
* Additional arguments to propagate to the subscriber
* @property args
* @type Array
*/
this.args = args;
/**
* Custom events for a given fire transaction.
* @property events
* @type {EventTarget}
*/
// this.events = null;
/**
* This listener only reacts to the event once
* @property once
*/
// this.once = false;
};
Y.Subscriber.prototype = {
constructor: Y.Subscriber,
_notify: function(c, args, ce) {
if (this.deleted && !this.postponed) {
if (this.postponed) {
delete this.fn;
delete this.context;
} else {
delete this.postponed;
return null;
}
}
var a = this.args, ret;
switch (ce.signature) {
case 0:
ret = this.fn.call(c, ce.type, args, c);
break;
case 1:
ret = this.fn.call(c, args[0] || null, c);
break;
default:
if (a || args) {
args = args || [];
a = (a) ? args.concat(a) : args;
ret = this.fn.apply(c, a);
} else {
ret = this.fn.call(c);
}
}
if (this.once) {
ce._delete(this);
}
return ret;
},
/**
* Executes the subscriber.
* @method notify
* @param args {Array} Arguments array for the subscriber.
* @param ce {CustomEvent} The custom event that sent the notification.
*/
notify: function(args, ce) {
var c = this.context,
ret = true;
if (!c) {
c = (ce.contextFn) ? ce.contextFn() : ce.context;
}
// only catch errors if we will not re-throw them.
if (Y.config.throwFail) {
ret = this._notify(c, args, ce);
} else {
try {
ret = this._notify(c, args, ce);
} catch (e) {
Y.error(this + ' failed: ' + e.message, e);
}
}
return ret;
},
/**
* Returns true if the fn and obj match this objects properties.
* Used by the unsubscribe method to match the right subscriber.
*
* @method contains
* @param {Function} fn the function to execute.
* @param {Object} context optional 'this' keyword for the listener.
* @return {boolean} true if the supplied arguments match this
* subscriber's signature.
*/
contains: function(fn, context) {
if (context) {
return ((this.fn == fn) && this.context == context);
} else {
return (this.fn == fn);
}
}
};
/**
* Return value from all subscribe operations
* @class EventHandle
* @constructor
* @param {CustomEvent} evt the custom event.
* @param {Subscriber} sub the subscriber.
*/
Y.EventHandle = function(evt, sub) {
/**
* The custom event
*
* @property evt
* @type CustomEvent
*/
this.evt = evt;
/**
* The subscriber object
*
* @property sub
* @type Subscriber
*/
this.sub = sub;
};
Y.EventHandle.prototype = {
batch: function(f, c) {
f.call(c || this, this);
if (Y.Lang.isArray(this.evt)) {
Y.Array.each(this.evt, function(h) {
h.batch.call(c || h, f);
});
}
},
/**
* Detaches this subscriber
* @method detach
* @return {int} the number of detached listeners
*/
detach: function() {
var evt = this.evt, detached = 0, i;
if (evt) {
// Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event');
if (Y.Lang.isArray(evt)) {
for (i = 0; i < evt.length; i++) {
detached += evt[i].detach();
}
} else {
evt._delete(this.sub);
detached = 1;
}
}
return detached;
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('attach', 'detach', 'publish').
* @return {EventHandle} return value from the monitor event subscription.
*/
monitor: function(what) {
return this.evt.monitor.apply(this.evt, arguments);
}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* EventTarget provides the implementation for any object to
* publish, subscribe and fire to custom events, and also
* alows other EventTargets to target the object with events
* sourced from the other object.
* EventTarget is designed to be used with Y.augment to wrap
* EventCustom in an interface that allows events to be listened to
* and fired by name. This makes it possible for implementing code to
* subscribe to an event that either has not been created yet, or will
* not be created at all.
* @class EventTarget
* @param opts a configuration object
* @config emitFacade {boolean} if true, all events will emit event
* facade payloads by default (default false)
* @config prefix {String} the prefix to apply to non-prefixed event names
*/
var L = Y.Lang,
PREFIX_DELIMITER = ':',
CATEGORY_DELIMITER = '|',
AFTER_PREFIX = '~AFTER~',
YArray = Y.Array,
_wildType = Y.cached(function(type) {
return type.replace(/(.*)(:)(.*)/, "*$2$3");
}),
/**
* If the instance has a prefix attribute and the
* event type is not prefixed, the instance prefix is
* applied to the supplied type.
* @method _getType
* @private
*/
_getType = Y.cached(function(type, pre) {
if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) {
return type;
}
return pre + PREFIX_DELIMITER + type;
}),
/**
* Returns an array with the detach key (if provided),
* and the prefixed event name from _getType
* Y.on('detachcategory| menu:click', fn)
* @method _parseType
* @private
*/
_parseType = Y.cached(function(type, pre) {
var t = type, detachcategory, after, i;
if (!L.isString(t)) {
return t;
}
i = t.indexOf(AFTER_PREFIX);
if (i > -1) {
after = true;
t = t.substr(AFTER_PREFIX.length);
// Y.log(t);
}
i = t.indexOf(CATEGORY_DELIMITER);
if (i > -1) {
detachcategory = t.substr(0, (i));
t = t.substr(i+1);
if (t == '*') {
t = null;
}
}
// detach category, full type with instance prefix, is this an after listener, short type
return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];
}),
ET = function(opts) {
// Y.log('EventTarget constructor executed: ' + this._yuid);
var o = (L.isObject(opts)) ? opts : {};
this._yuievt = this._yuievt || {
id: Y.guid(),
events: {},
targets: {},
config: o,
chain: ('chain' in o) ? o.chain : Y.config.chain,
bubbling: false,
defaults: {
context: o.context || this,
host: this,
emitFacade: o.emitFacade,
fireOnce: o.fireOnce,
queuable: o.queuable,
monitored: o.monitored,
broadcast: o.broadcast,
defaultTargetOnly: o.defaultTargetOnly,
bubbles: ('bubbles' in o) ? o.bubbles : true
}
};
};
ET.prototype = {
constructor: ET,
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>on</code> except the
* listener is immediatelly detached when it is executed.
* @method once
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
once: function() {
var handle = this.on.apply(this, arguments);
handle.batch(function(hand) {
if (hand.sub) {
hand.sub.once = true;
}
});
return handle;
},
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>after</code> except the
* listener is immediatelly detached when it is executed.
* @method onceAfter
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
onceAfter: function() {
var handle = this.after.apply(this, arguments);
handle.batch(function(hand) {
if (hand.sub) {
hand.sub.once = true;
}
});
return handle;
},
/**
* Takes the type parameter passed to 'on' and parses out the
* various pieces that could be included in the type. If the
* event type is passed without a prefix, it will be expanded
* to include the prefix one is supplied or the event target
* is configured with a default prefix.
* @method parseType
* @param {String} type the type
* @param {String} [pre=this._yuievt.config.prefix] the prefix
* @since 3.3.0
* @return {Array} an array containing:
* * the detach category, if supplied,
* * the prefixed event type,
* * whether or not this is an after listener,
* * the supplied event type
*/
parseType: function(type, pre) {
return _parseType(type, pre || this._yuievt.config.prefix);
},
/**
* Subscribe a callback function to a custom event fired by this object or
* from an object that bubbles its events to this object.
*
* Callback functions for events published with `emitFacade = true` will
* receive an `EventFacade` as the first argument (typically named "e").
* These callbacks can then call `e.preventDefault()` to disable the
* behavior published to that event's `defaultFn`. See the `EventFacade`
* API for all available properties and methods. Subscribers to
* non-`emitFacade` events will receive the arguments passed to `fire()`
* after the event name.
*
* To subscribe to multiple events at once, pass an object as the first
* argument, where the key:value pairs correspond to the eventName:callback,
* or pass an array of event names as the first argument to subscribe to
* all listed events with the same callback.
*
* Returning `false` from a callback is supported as an alternative to
* calling `e.preventDefault(); e.stopPropagation();`. However, it is
* recommended to use the event methods whenever possible.
*
* @method on
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
on: function(type, fn, context) {
var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce,
detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,
Node = Y.Node, n, domevent, isArr;
// full name, args, detachcategory, after
this._monitor('attach', parts[1], {
args: arguments,
category: parts[0],
after: parts[2]
});
if (L.isObject(type)) {
if (L.isFunction(type)) {
return Y.Do.before.apply(Y.Do, arguments);
}
f = fn;
c = context;
args = YArray(arguments, 0, true);
ret = [];
if (L.isArray(type)) {
isArr = true;
}
after = type._after;
delete type._after;
Y.each(type, function(v, k) {
if (L.isObject(v)) {
f = v.fn || ((L.isFunction(v)) ? v : f);
c = v.context || c;
}
var nv = (after) ? AFTER_PREFIX : '';
args[0] = nv + ((isArr) ? v : k);
args[1] = f;
args[2] = c;
ret.push(this.on.apply(this, args));
}, this);
return (this._yuievt.chain) ? this : new Y.EventHandle(ret);
}
detachcategory = parts[0];
after = parts[2];
shorttype = parts[3];
// extra redirection so we catch adaptor events too. take a look at this.
if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) {
args = YArray(arguments, 0, true);
args.splice(2, 0, Node.getDOMNode(this));
// Y.log("Node detected, redirecting with these args: " + args);
return Y.on.apply(Y, args);
}
type = parts[1];
if (Y.instanceOf(this, YUI)) {
adapt = Y.Env.evt.plugins[type];
args = YArray(arguments, 0, true);
args[0] = shorttype;
if (Node) {
n = args[2];
if (Y.instanceOf(n, Y.NodeList)) {
n = Y.NodeList.getDOMNodes(n);
} else if (Y.instanceOf(n, Node)) {
n = Node.getDOMNode(n);
}
domevent = (shorttype in Node.DOM_EVENTS);
// Captures both DOM events and event plugins.
if (domevent) {
args[2] = n;
}
}
// check for the existance of an event adaptor
if (adapt) {
Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event');
handle = adapt.on.apply(Y, args);
} else if ((!type) || domevent) {
handle = Y.Event._attach(args);
}
}
if (!handle) {
ce = this._yuievt.events[type] || this.publish(type);
handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true);
}
if (detachcategory) {
store[detachcategory] = store[detachcategory] || {};
store[detachcategory][type] = store[detachcategory][type] || [];
store[detachcategory][type].push(handle);
}
return (this._yuievt.chain) ? this : handle;
},
/**
* subscribe to an event
* @method subscribe
* @deprecated use on
*/
subscribe: function() {
Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated');
return this.on.apply(this, arguments);
},
/**
* Detach one or more listeners the from the specified event
* @method detach
* @param type {string|Object} Either the handle to the subscriber or the
* type of event. If the type
* is not specified, it will attempt to remove
* the listener from all hosted events.
* @param fn {Function} The subscribed function to unsubscribe, if not
* supplied, all subscribers will be removed.
* @param context {Object} The custom object passed to subscribe. This is
* optional, but if supplied will be used to
* disambiguate multiple listeners that are the same
* (e.g., you subscribe many object using a function
* that lives on the prototype)
* @return {EventTarget} the host
*/
detach: function(type, fn, context) {
var evts = this._yuievt.events, i,
Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node));
// detachAll disabled on the Y instance.
if (!type && (this !== Y)) {
for (i in evts) {
if (evts.hasOwnProperty(i)) {
evts[i].detach(fn, context);
}
}
if (isNode) {
Y.Event.purgeElement(Node.getDOMNode(this));
}
return this;
}
var parts = _parseType(type, this._yuievt.config.prefix),
detachcategory = L.isArray(parts) ? parts[0] : null,
shorttype = (parts) ? parts[3] : null,
adapt, store = Y.Env.evt.handles, detachhost, cat, args,
ce,
keyDetacher = function(lcat, ltype, host) {
var handles = lcat[ltype], ce, i;
if (handles) {
for (i = handles.length - 1; i >= 0; --i) {
ce = handles[i].evt;
if (ce.host === host || ce.el === host) {
handles[i].detach();
}
}
}
};
if (detachcategory) {
cat = store[detachcategory];
type = parts[1];
detachhost = (isNode) ? Y.Node.getDOMNode(this) : this;
if (cat) {
if (type) {
keyDetacher(cat, type, detachhost);
} else {
for (i in cat) {
if (cat.hasOwnProperty(i)) {
keyDetacher(cat, i, detachhost);
}
}
}
return this;
}
// If this is an event handle, use it to detach
} else if (L.isObject(type) && type.detach) {
type.detach();
return this;
// extra redirection so we catch adaptor events too. take a look at this.
} else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {
args = YArray(arguments, 0, true);
args[2] = Node.getDOMNode(this);
Y.detach.apply(Y, args);
return this;
}
adapt = Y.Env.evt.plugins[shorttype];
// The YUI instance handles DOM events and adaptors
if (Y.instanceOf(this, YUI)) {
args = YArray(arguments, 0, true);
// use the adaptor specific detach code if
if (adapt && adapt.detach) {
adapt.detach.apply(Y, args);
return this;
// DOM event fork
} else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {
args[0] = type;
Y.Event.detach.apply(Y.Event, args);
return this;
}
}
// ce = evts[type];
ce = evts[parts[1]];
if (ce) {
ce.detach(fn, context);
}
return this;
},
/**
* detach a listener
* @method unsubscribe
* @deprecated use detach
*/
unsubscribe: function() {
Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated');
return this.detach.apply(this, arguments);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method detachAll
* @param type {String} The type, or name of the event
*/
detachAll: function(type) {
return this.detach(type);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method unsubscribeAll
* @param type {String} The type, or name of the event
* @deprecated use detachAll
*/
unsubscribeAll: function() {
Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated');
return this.detachAll.apply(this, arguments);
},
/**
* Creates a new custom event of the specified type. If a custom event
* by that name already exists, it will not be re-created. In either
* case the custom event is returned.
*
* @method publish
*
* @param type {String} the type, or name of the event
* @param opts {object} optional config params. Valid properties are:
*
* <ul>
* <li>
* 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false)
* </li>
* <li>
* 'bubbles': whether or not this event bubbles (true)
* Events can only bubble if emitFacade is true.
* </li>
* <li>
* 'context': the default execution context for the listeners (this)
* </li>
* <li>
* 'defaultFn': the default function to execute when this event fires if preventDefault was not called
* </li>
* <li>
* 'emitFacade': whether or not this event emits a facade (false)
* </li>
* <li>
* 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click'
* </li>
* <li>
* 'fireOnce': if an event is configured to fire once, new subscribers after
* the fire will be notified immediately.
* </li>
* <li>
* 'async': fireOnce event listeners will fire synchronously if the event has already
* fired unless async is true.
* </li>
* <li>
* 'preventable': whether or not preventDefault() has an effect (true)
* </li>
* <li>
* 'preventedFn': a function that is executed when preventDefault is called
* </li>
* <li>
* 'queuable': whether or not this event can be queued during bubbling (false)
* </li>
* <li>
* 'silent': if silent is true, debug messages are not provided for this event.
* </li>
* <li>
* 'stoppedFn': a function that is executed when stopPropagation is called
* </li>
*
* <li>
* 'monitored': specifies whether or not this event should send notifications about
* when the event has been attached, detached, or published.
* </li>
* <li>
* 'type': the event type (valid option if not provided as the first parameter to publish)
* </li>
* </ul>
*
* @return {CustomEvent} the custom event
*
*/
publish: function(type, opts) {
var events, ce, ret, defaults,
edata = this._yuievt,
pre = edata.config.prefix;
if (L.isObject(type)) {
ret = {};
Y.each(type, function(v, k) {
ret[k] = this.publish(k, v || opts);
}, this);
return ret;
}
type = (pre) ? _getType(type, pre) : type;
this._monitor('publish', type, {
args: arguments
});
events = edata.events;
ce = events[type];
if (ce) {
// ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event');
if (opts) {
ce.applyConfig(opts, true);
}
} else {
defaults = edata.defaults;
// apply defaults
ce = new Y.CustomEvent(type,
(opts) ? Y.merge(defaults, opts) : defaults);
events[type] = ce;
}
// make sure we turn the broadcast flag off if this
// event was published as a result of bubbling
// if (opts instanceof Y.CustomEvent) {
// events[type].broadcast = false;
// }
return events[type];
},
/**
* This is the entry point for the event monitoring system.
* You can monitor 'attach', 'detach', 'fire', and 'publish'.
* When configured, these events generate an event. click ->
* click_attach, click_detach, click_publish -- these can
* be subscribed to like other events to monitor the event
* system. Inividual published events can have monitoring
* turned on or off (publish can't be turned off before it
* it published) by setting the events 'monitor' config.
*
* @method _monitor
* @param what {String} 'attach', 'detach', 'fire', or 'publish'
* @param type {String} Name of the event being monitored
* @param o {Object} Information about the event interaction, such as
* fire() args, subscription category, publish config
* @private
*/
_monitor: function(what, type, o) {
var monitorevt, ce = this.getEvent(type);
if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
monitorevt = type + '_' + what;
// Y.log('monitoring: ' + monitorevt);
o.monitored = what;
this.fire.call(this, monitorevt, o);
}
},
/**
* Fire a custom event by name. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters.
*
* If the custom event object hasn't been created, then the event hasn't
* been published and it has no subscribers. For performance sake, we
* immediate exit in this case. This means the event won't bubble, so
* if the intention is that a bubble target be notified, the event must
* be published on this object first.
*
* The first argument is the event type, and any additional arguments are
* passed to the listeners as parameters. If the first of these is an
* object literal, and the event is configured to emit an event facade,
* that object is mixed into the event facade and the facade is provided
* in place of the original object.
*
* @method fire
* @param type {String|Object} The type of the event, or an object that contains
* a 'type' property.
* @param arguments {Object*} an arbitrary set of parameters to pass to
* the handler. If the first of these is an object literal and the event is
* configured to emit an event facade, the event facade will replace that
* parameter after the properties the object literal contains are copied to
* the event facade.
* @return {EventTarget} the event host
*
*/
fire: function(type) {
var typeIncluded = L.isString(type),
t = (typeIncluded) ? type : (type && type.type),
ce, ret, pre = this._yuievt.config.prefix, ce2,
args = (typeIncluded) ? YArray(arguments, 1, true) : arguments;
t = (pre) ? _getType(t, pre) : t;
this._monitor('fire', t, {
args: args
});
ce = this.getEvent(t, true);
ce2 = this.getSibling(t, ce);
if (ce2 && !ce) {
ce = this.publish(t);
}
// this event has not been published or subscribed to
if (!ce) {
if (this._yuievt.hasTargets) {
return this.bubble({ type: t }, args, this);
}
// otherwise there is nothing to be done
ret = true;
} else {
ce.sibling = ce2;
ret = ce.fire.apply(ce, args);
}
return (this._yuievt.chain) ? this : ret;
},
getSibling: function(type, ce) {
var ce2;
// delegate to *:type events if there are subscribers
if (type.indexOf(PREFIX_DELIMITER) > -1) {
type = _wildType(type);
// console.log(type);
ce2 = this.getEvent(type, true);
if (ce2) {
// console.log("GOT ONE: " + type);
ce2.applyConfig(ce);
ce2.bubbles = false;
ce2.broadcast = 0;
// ret = ce2.fire.apply(ce2, a);
}
}
return ce2;
},
/**
* Returns the custom event of the provided type has been created, a
* falsy value otherwise
* @method getEvent
* @param type {String} the type, or name of the event
* @param prefixed {String} if true, the type is prefixed already
* @return {CustomEvent} the custom event or null
*/
getEvent: function(type, prefixed) {
var pre, e;
if (!prefixed) {
pre = this._yuievt.config.prefix;
type = (pre) ? _getType(type, pre) : type;
}
e = this._yuievt.events;
return e[type] || null;
},
/**
* Subscribe to a custom event hosted by this object. The
* supplied callback will execute after any listeners add
* via the subscribe method, and after the default function,
* if configured for the event, has executed.
*
* @method after
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
after: function(type, fn) {
var a = YArray(arguments, 0, true);
switch (L.type(type)) {
case 'function':
return Y.Do.after.apply(Y.Do, arguments);
case 'array':
// YArray.each(a[0], function(v) {
// v = AFTER_PREFIX + v;
// });
// break;
case 'object':
a[0]._after = true;
break;
default:
a[0] = AFTER_PREFIX + type;
}
return this.on.apply(this, a);
},
/**
* Executes the callback before a DOM event, custom event
* or method. If the first argument is a function, it
* is assumed the target is a method. For DOM and custom
* events, this is an alias for Y.on.
*
* For DOM and custom events:
* type, callback, context, 0-n arguments
*
* For methods:
* callback, object (method host), methodName, context, 0-n arguments
*
* @method before
* @return detach handle
*/
before: function() {
return this.on.apply(this, arguments);
}
};
Y.EventTarget = ET;
// make Y an event target
Y.mix(Y, ET.prototype);
ET.call(Y, { bubbles: false });
YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();
/**
* Hosts YUI page level events. This is where events bubble to
* when the broadcast config is set to 2. This property is
* only available if the custom event module is loaded.
* @property Global
* @type EventTarget
* @for YUI
*/
Y.Global = YUI.Env.globalEvents;
// @TODO implement a global namespace function on Y.Global?
/**
`Y.on()` can do many things:
<ul>
<li>Subscribe to custom events `publish`ed and `fire`d from Y</li>
<li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and
`fire`d from any object in the YUI instance sandbox</li>
<li>Subscribe to DOM events</li>
<li>Subscribe to the execution of a method on any object, effectively
treating that method as an event</li>
</ul>
For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument.
Y.on('io:complete', function () {
Y.MyApp.updateStatus('Transaction complete');
});
To subscribe to DOM events, pass the name of a DOM event as the first argument
and a CSS selector string as the third argument after the callback function.
Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`,
array, or simply omitted (the default is the `window` object).
Y.on('click', function (e) {
e.preventDefault();
// proceed with ajax form submission
var url = this.get('action');
...
}, '#my-form');
The `this` object in DOM event callbacks will be the `Node` targeted by the CSS
selector or other identifier.
`on()` subscribers for DOM events or custom events `publish`ed with a
`defaultFn` can prevent the default behavior with `e.preventDefault()` from the
event object passed as the first parameter to the subscription callback.
To subscribe to the execution of an object method, pass arguments corresponding to the call signature for
<a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>.
NOTE: The formal parameter list below is for events, not for function
injection. See `Y.Do.before` for that signature.
@method on
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@see Do.before
@for YUI
**/
/**
Listen for an event one time. Equivalent to `on()`, except that
the listener is immediately detached when executed.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
@see on
@method once
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Listen for an event one time. Equivalent to `once()`, except, like `after()`,
the subscription callback executes after all `on()` subscribers and the event's
`defaultFn` (if configured) have executed. Like `after()` if any `on()` phase
subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()`
subscribers will execute.
The listener is immediately detached when executed.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
@see once
@method onceAfter
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Like `on()`, this method creates a subscription to a custom event or to the
execution of a method on an object.
For events, `after()` subscribers are executed after the event's
`defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
NOTE: The subscription signature shown is for events, not for function
injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a>
for that signature.
@see on
@see Do.after
@method after
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [args*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
}, '@VERSION@' ,{requires:['oop']});
YUI.add('event-custom-complex', function(Y) {
/**
* Adds event facades, preventable default behavior, and bubbling.
* events.
* @module event-custom
* @submodule event-custom-complex
*/
var FACADE,
FACADE_KEYS,
EMPTY = {},
CEProto = Y.CustomEvent.prototype,
ETProto = Y.EventTarget.prototype;
/**
* Wraps and protects a custom event for use when emitFacade is set to true.
* Requires the event-custom-complex module
* @class EventFacade
* @param e {Event} the custom event
* @param currentTarget {HTMLElement} the element the listener was attached to
*/
Y.EventFacade = function(e, currentTarget) {
e = e || EMPTY;
this._event = e;
/**
* The arguments passed to fire
* @property details
* @type Array
*/
this.details = e.details;
/**
* The event type, this can be overridden by the fire() payload
* @property type
* @type string
*/
this.type = e.type;
/**
* The real event type
* @property _type
* @type string
* @private
*/
this._type = e.type;
//////////////////////////////////////////////////////
/**
* Node reference for the targeted eventtarget
* @property target
* @type Node
*/
this.target = e.target;
/**
* Node reference for the element that the listener was attached to.
* @property currentTarget
* @type Node
*/
this.currentTarget = currentTarget;
/**
* Node reference to the relatedTarget
* @property relatedTarget
* @type Node
*/
this.relatedTarget = e.relatedTarget;
};
Y.extend(Y.EventFacade, Object, {
/**
* Stops the propagation to the next bubble target
* @method stopPropagation
*/
stopPropagation: function() {
this._event.stopPropagation();
this.stopped = 1;
},
/**
* Stops the propagation to the next bubble target and
* prevents any additional listeners from being exectued
* on the current target.
* @method stopImmediatePropagation
*/
stopImmediatePropagation: function() {
this._event.stopImmediatePropagation();
this.stopped = 2;
},
/**
* Prevents the event's default behavior
* @method preventDefault
*/
preventDefault: function() {
this._event.preventDefault();
this.prevented = 1;
},
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
halt: function(immediate) {
this._event.halt(immediate);
this.prevented = 1;
this.stopped = (immediate) ? 2 : 1;
}
});
CEProto.fireComplex = function(args) {
var es, ef, q, queue, ce, ret, events, subs, postponed,
self = this, host = self.host || self, next, oldbubble;
if (self.stack) {
// queue this event if the current item in the queue bubbles
if (self.queuable && self.type != self.stack.next.type) {
self.log('queue ' + self.type);
self.stack.queue.push([self, args]);
return true;
}
}
es = self.stack || {
// id of the first event in the stack
id: self.id,
next: self,
silent: self.silent,
stopped: 0,
prevented: 0,
bubbling: null,
type: self.type,
// defaultFnQueue: new Y.Queue(),
afterQueue: new Y.Queue(),
defaultTargetOnly: self.defaultTargetOnly,
queue: []
};
subs = self.getSubs();
self.stopped = (self.type !== es.type) ? 0 : es.stopped;
self.prevented = (self.type !== es.type) ? 0 : es.prevented;
self.target = self.target || host;
events = new Y.EventTarget({
fireOnce: true,
context: host
});
self.events = events;
if (self.stoppedFn) {
events.on('stopped', self.stoppedFn);
}
self.currentTarget = host;
self.details = args.slice(); // original arguments in the details
// self.log("Firing " + self + ", " + "args: " + args);
self.log("Firing " + self.type);
self._facade = null; // kill facade to eliminate stale properties
ef = self._getFacade(args);
if (Y.Lang.isObject(args[0])) {
args[0] = ef;
} else {
args.unshift(ef);
}
// if (subCount) {
if (subs[0]) {
// self._procSubs(Y.merge(self.subscribers), args, ef);
self._procSubs(subs[0], args, ef);
}
// bubble if this is hosted in an event target and propagation has not been stopped
if (self.bubbles && host.bubble && !self.stopped) {
oldbubble = es.bubbling;
// self.bubbling = true;
es.bubbling = self.type;
// if (host !== ef.target || es.type != self.type) {
if (es.type != self.type) {
es.stopped = 0;
es.prevented = 0;
}
ret = host.bubble(self, args, null, es);
self.stopped = Math.max(self.stopped, es.stopped);
self.prevented = Math.max(self.prevented, es.prevented);
// self.bubbling = false;
es.bubbling = oldbubble;
}
if (self.prevented) {
if (self.preventedFn) {
self.preventedFn.apply(host, args);
}
} else if (self.defaultFn &&
((!self.defaultTargetOnly && !es.defaultTargetOnly) ||
host === ef.target)) {
self.defaultFn.apply(host, args);
}
// broadcast listeners are fired as discreet events on the
// YUI instance and potentially the YUI global.
self._broadcast(args);
// Queue the after
if (subs[1] && !self.prevented && self.stopped < 2) {
if (es.id === self.id || self.type != host._yuievt.bubbling) {
self._procSubs(subs[1], args, ef);
while ((next = es.afterQueue.last())) {
next();
}
} else {
postponed = subs[1];
if (es.execDefaultCnt) {
postponed = Y.merge(postponed);
Y.each(postponed, function(s) {
s.postponed = true;
});
}
es.afterQueue.add(function() {
self._procSubs(postponed, args, ef);
});
}
}
self.target = null;
if (es.id === self.id) {
queue = es.queue;
while (queue.length) {
q = queue.pop();
ce = q[0];
// set up stack to allow the next item to be processed
es.next = ce;
ce.fire.apply(ce, q[1]);
}
self.stack = null;
}
ret = !(self.stopped);
if (self.type != host._yuievt.bubbling) {
es.stopped = 0;
es.prevented = 0;
self.stopped = 0;
self.prevented = 0;
}
return ret;
};
CEProto._getFacade = function() {
var ef = this._facade, o, o2,
args = this.details;
if (!ef) {
ef = new Y.EventFacade(this, this.currentTarget);
}
// if the first argument is an object literal, apply the
// properties to the event facade
o = args && args[0];
if (Y.Lang.isObject(o, true)) {
o2 = {};
// protect the event facade properties
Y.mix(o2, ef, true, FACADE_KEYS);
// mix the data
Y.mix(ef, o, true);
// restore ef
Y.mix(ef, o2, true, FACADE_KEYS);
// Allow the event type to be faked
// http://yuilibrary.com/projects/yui3/ticket/2528376
ef.type = o.type || ef.type;
}
// update the details field with the arguments
// ef.type = this.type;
ef.details = this.details;
// use the original target when the event bubbled to this target
ef.target = this.originalTarget || this.target;
ef.currentTarget = this.currentTarget;
ef.stopped = 0;
ef.prevented = 0;
this._facade = ef;
return this._facade;
};
/**
* Stop propagation to bubble targets
* @for CustomEvent
* @method stopPropagation
*/
CEProto.stopPropagation = function() {
this.stopped = 1;
if (this.stack) {
this.stack.stopped = 1;
}
this.events.fire('stopped', this);
};
/**
* Stops propagation to bubble targets, and prevents any remaining
* subscribers on the current target from executing.
* @method stopImmediatePropagation
*/
CEProto.stopImmediatePropagation = function() {
this.stopped = 2;
if (this.stack) {
this.stack.stopped = 2;
}
this.events.fire('stopped', this);
};
/**
* Prevents the execution of this event's defaultFn
* @method preventDefault
*/
CEProto.preventDefault = function() {
if (this.preventable) {
this.prevented = 1;
if (this.stack) {
this.stack.prevented = 1;
}
}
};
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
CEProto.halt = function(immediate) {
if (immediate) {
this.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this.preventDefault();
};
/**
* Registers another EventTarget as a bubble target. Bubble order
* is determined by the order registered. Multiple targets can
* be specified.
*
* Events can only bubble if emitFacade is true.
*
* Included in the event-custom-complex submodule.
*
* @method addTarget
* @param o {EventTarget} the target to add
* @for EventTarget
*/
ETProto.addTarget = function(o) {
this._yuievt.targets[Y.stamp(o)] = o;
this._yuievt.hasTargets = true;
};
/**
* Returns an array of bubble targets for this object.
* @method getTargets
* @return EventTarget[]
*/
ETProto.getTargets = function() {
return Y.Object.values(this._yuievt.targets);
};
/**
* Removes a bubble target
* @method removeTarget
* @param o {EventTarget} the target to remove
* @for EventTarget
*/
ETProto.removeTarget = function(o) {
delete this._yuievt.targets[Y.stamp(o)];
};
/**
* Propagate an event. Requires the event-custom-complex module.
* @method bubble
* @param evt {CustomEvent} the custom event to propagate
* @return {boolean} the aggregated return value from Event.Custom.fire
* @for EventTarget
*/
ETProto.bubble = function(evt, args, target, es) {
var targs = this._yuievt.targets, ret = true,
t, type = evt && evt.type, ce, i, bc, ce2,
originalTarget = target || (evt && evt.target) || this,
oldbubble;
if (!evt || ((!evt.stopped) && targs)) {
// Y.log('Bubbling ' + evt.type);
for (i in targs) {
if (targs.hasOwnProperty(i)) {
t = targs[i];
ce = t.getEvent(type, true);
ce2 = t.getSibling(type, ce);
if (ce2 && !ce) {
ce = t.publish(type);
}
oldbubble = t._yuievt.bubbling;
t._yuievt.bubbling = type;
// if this event was not published on the bubble target,
// continue propagating the event.
if (!ce) {
if (t._yuievt.hasTargets) {
t.bubble(evt, args, originalTarget, es);
}
} else {
ce.sibling = ce2;
// set the original target to that the target payload on the
// facade is correct.
ce.target = originalTarget;
ce.originalTarget = originalTarget;
ce.currentTarget = t;
bc = ce.broadcast;
ce.broadcast = false;
// default publish may not have emitFacade true -- that
// shouldn't be what the implementer meant to do
ce.emitFacade = true;
ce.stack = es;
ret = ret && ce.fire.apply(ce, args || evt.details || []);
ce.broadcast = bc;
ce.originalTarget = null;
// stopPropagation() was called
if (ce.stopped) {
break;
}
}
t._yuievt.bubbling = oldbubble;
}
}
}
return ret;
};
FACADE = new Y.EventFacade();
FACADE_KEYS = Y.Object.keys(FACADE);
}, '@VERSION@' ,{requires:['event-custom-base']});
YUI.add('node-core', function(Y) {
/**
* The Node Utility provides a DOM-like interface for interacting with DOM nodes.
* @module node
* @main node
* @submodule node-core
*/
/**
* The Node class provides a wrapper for manipulating DOM Nodes.
* Node properties can be accessed via the set/get methods.
* Use `Y.one()` to retrieve Node instances.
*
* <strong>NOTE:</strong> Node properties are accessed using
* the <code>set</code> and <code>get</code> methods.
*
* @class Node
* @constructor
* @param {DOMNode} node the DOM node to be mapped to the Node instance.
* @uses EventTarget
*/
// "globals"
var DOT = '.',
NODE_NAME = 'nodeName',
NODE_TYPE = 'nodeType',
OWNER_DOCUMENT = 'ownerDocument',
TAG_NAME = 'tagName',
UID = '_yuid',
EMPTY_OBJ = {},
_slice = Array.prototype.slice,
Y_DOM = Y.DOM,
Y_Node = function(node) {
if (!this.getDOMNode) { // support optional "new"
return new Y_Node(node);
}
if (typeof node == 'string') {
node = Y_Node._fromString(node);
if (!node) {
return null; // NOTE: return
}
}
var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID];
if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) {
node[UID] = null; // unset existing uid to prevent collision (via clone or hack)
}
uid = uid || Y.stamp(node);
if (!uid) { // stamp failed; likely IE non-HTMLElement
uid = Y.guid();
}
this[UID] = uid;
/**
* The underlying DOM node bound to the Y.Node instance
* @property _node
* @private
*/
this._node = node;
this._stateProxy = node; // when augmented with Attribute
if (this._initPlugins) { // when augmented with Plugin.Host
this._initPlugins();
}
},
// used with previous/next/ancestor tests
_wrapFn = function(fn) {
var ret = null;
if (fn) {
ret = (typeof fn == 'string') ?
function(n) {
return Y.Selector.test(n, fn);
} :
function(n) {
return fn(Y.one(n));
};
}
return ret;
};
// end "globals"
Y_Node.ATTRS = {};
Y_Node.DOM_EVENTS = {};
Y_Node._fromString = function(node) {
if (node) {
if (node.indexOf('doc') === 0) { // doc OR document
node = Y.config.doc;
} else if (node.indexOf('win') === 0) { // win OR window
node = Y.config.win;
} else {
node = Y.Selector.query(node, null, true);
}
}
return node || null;
};
/**
* The name of the component
* @static
* @property NAME
*/
Y_Node.NAME = 'node';
/*
* The pattern used to identify ARIA attributes
*/
Y_Node.re_aria = /^(?:role$|aria-)/;
Y_Node.SHOW_TRANSITION = 'fadeIn';
Y_Node.HIDE_TRANSITION = 'fadeOut';
/**
* A list of Node instances that have been created
* @private
* @property _instances
* @static
*
*/
Y_Node._instances = {};
/**
* Retrieves the DOM node bound to a Node instance
* @method getDOMNode
* @static
*
* @param {Node | HTMLNode} node The Node instance or an HTMLNode
* @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed
* as the node argument, it is simply returned.
*/
Y_Node.getDOMNode = function(node) {
if (node) {
return (node.nodeType) ? node : node._node || null;
}
return null;
};
/**
* Checks Node return values and wraps DOM Nodes as Y.Node instances
* and DOM Collections / Arrays as Y.NodeList instances.
* Other return values just pass thru. If undefined is returned (e.g. no return)
* then the Node instance is returned for chainability.
* @method scrubVal
* @static
*
* @param {any} node The Node instance or an HTMLNode
* @return {Node | NodeList | Any} Depends on what is returned from the DOM node.
*/
Y_Node.scrubVal = function(val, node) {
if (val) { // only truthy values are risky
if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function
if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window
val = Y.one(val);
} else if ((val.item && !val._nodes) || // dom collection or Node instance
(val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes
val = Y.all(val);
}
}
} else if (typeof val === 'undefined') {
val = node; // for chaining
} else if (val === null) {
val = null; // IE: DOM null not the same as null
}
return val;
};
/**
* Adds methods to the Y.Node prototype, routing through scrubVal.
* @method addMethod
* @static
*
* @param {String} name The name of the method to add
* @param {Function} fn The function that becomes the method
* @param {Object} context An optional context to call the method with
* (defaults to the Node instance)
* @return {any} Depends on what is returned from the DOM node.
*/
Y_Node.addMethod = function(name, fn, context) {
if (name && fn && typeof fn == 'function') {
Y_Node.prototype[name] = function() {
var args = _slice.call(arguments),
node = this,
ret;
if (args[0] && args[0]._node) {
args[0] = args[0]._node;
}
if (args[1] && args[1]._node) {
args[1] = args[1]._node;
}
args.unshift(node._node);
ret = fn.apply(node, args);
if (ret) { // scrub truthy
ret = Y_Node.scrubVal(ret, node);
}
(typeof ret != 'undefined') || (ret = node);
return ret;
};
} else {
Y.log('unable to add method: ' + name, 'warn', 'Node');
}
};
/**
* Imports utility methods to be added as Y.Node methods.
* @method importMethod
* @static
*
* @param {Object} host The object that contains the method to import.
* @param {String} name The name of the method to import
* @param {String} altName An optional name to use in place of the host name
* @param {Object} context An optional context to call the method with
*/
Y_Node.importMethod = function(host, name, altName) {
if (typeof name == 'string') {
altName = altName || name;
Y_Node.addMethod(altName, host[name], host);
} else {
Y.Array.each(name, function(n) {
Y_Node.importMethod(host, n);
});
}
};
/**
* Retrieves a NodeList based on the given CSS selector.
* @method all
*
* @param {string} selector The CSS selector to test against.
* @return {NodeList} A NodeList instance for the matching HTMLCollection/Array.
* @for YUI
*/
/**
* Returns a single Node instance bound to the node or the
* first element matching the given selector. Returns null if no match found.
* <strong>Note:</strong> For chaining purposes you may want to
* use <code>Y.all</code>, which returns a NodeList when no match is found.
* @method one
* @param {String | HTMLElement} node a node or Selector
* @return {Node | null} a Node instance or null if no match found.
* @for YUI
*/
/**
* Returns a single Node instance bound to the node or the
* first element matching the given selector. Returns null if no match found.
* <strong>Note:</strong> For chaining purposes you may want to
* use <code>Y.all</code>, which returns a NodeList when no match is found.
* @method one
* @static
* @param {String | HTMLElement} node a node or Selector
* @return {Node | null} a Node instance or null if no match found.
* @for Node
*/
Y_Node.one = function(node) {
var instance = null,
cachedNode,
uid;
if (node) {
if (typeof node == 'string') {
node = Y_Node._fromString(node);
if (!node) {
return null; // NOTE: return
}
} else if (node.getDOMNode) {
return node; // NOTE: return
}
if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc)
uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid;
instance = Y_Node._instances[uid]; // reuse exising instances
cachedNode = instance ? instance._node : null;
if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match
instance = new Y_Node(node);
if (node.nodeType != 11) { // dont cache document fragment
Y_Node._instances[instance[UID]] = instance; // cache node
}
}
}
}
return instance;
};
/**
* The default setter for DOM properties
* Called with instance context (this === the Node instance)
* @method DEFAULT_SETTER
* @static
* @param {String} name The attribute/property being set
* @param {any} val The value to be set
* @return {any} The value
*/
Y_Node.DEFAULT_SETTER = function(name, val) {
var node = this._stateProxy,
strPath;
if (name.indexOf(DOT) > -1) {
strPath = name;
name = name.split(DOT);
// only allow when defined on node
Y.Object.setValue(node, name, val);
} else if (typeof node[name] != 'undefined') { // pass thru DOM properties
node[name] = val;
}
return val;
};
/**
* The default getter for DOM properties
* Called with instance context (this === the Node instance)
* @method DEFAULT_GETTER
* @static
* @param {String} name The attribute/property to look up
* @return {any} The current value
*/
Y_Node.DEFAULT_GETTER = function(name) {
var node = this._stateProxy,
val;
if (name.indexOf && name.indexOf(DOT) > -1) {
val = Y.Object.getValue(node, name.split(DOT));
} else if (typeof node[name] != 'undefined') { // pass thru from DOM
val = node[name];
}
return val;
};
Y.mix(Y_Node.prototype, {
DATA_PREFIX: 'data-',
/**
* The method called when outputting Node instances as strings
* @method toString
* @return {String} A string representation of the Node instance
*/
toString: function() {
var str = this[UID] + ': not bound to a node',
node = this._node,
attrs, id, className;
if (node) {
attrs = node.attributes;
id = (attrs && attrs.id) ? node.getAttribute('id') : null;
className = (attrs && attrs.className) ? node.getAttribute('className') : null;
str = node[NODE_NAME];
if (id) {
str += '#' + id;
}
if (className) {
str += '.' + className.replace(' ', '.');
}
// TODO: add yuid?
str += ' ' + this[UID];
}
return str;
},
/**
* Returns an attribute value on the Node instance.
* Unless pre-configured (via `Node.ATTRS`), get hands
* off to the underlying DOM node. Only valid
* attributes/properties for the node will be queried.
* @method get
* @param {String} attr The attribute
* @return {any} The current value of the attribute
*/
get: function(attr) {
var val;
if (this._getAttr) { // use Attribute imple
val = this._getAttr(attr);
} else {
val = this._get(attr);
}
if (val) {
val = Y_Node.scrubVal(val, this);
} else if (val === null) {
val = null; // IE: DOM null is not true null (even though they ===)
}
return val;
},
/**
* Helper method for get.
* @method _get
* @private
* @param {String} attr The attribute
* @return {any} The current value of the attribute
*/
_get: function(attr) {
var attrConfig = Y_Node.ATTRS[attr],
val;
if (attrConfig && attrConfig.getter) {
val = attrConfig.getter.call(this);
} else if (Y_Node.re_aria.test(attr)) {
val = this._node.getAttribute(attr, 2);
} else {
val = Y_Node.DEFAULT_GETTER.apply(this, arguments);
}
return val;
},
/**
* Sets an attribute on the Node instance.
* Unless pre-configured (via Node.ATTRS), set hands
* off to the underlying DOM node. Only valid
* attributes/properties for the node will be set.
* To set custom attributes use setAttribute.
* @method set
* @param {String} attr The attribute to be set.
* @param {any} val The value to set the attribute to.
* @chainable
*/
set: function(attr, val) {
var attrConfig = Y_Node.ATTRS[attr];
if (this._setAttr) { // use Attribute imple
this._setAttr.apply(this, arguments);
} else { // use setters inline
if (attrConfig && attrConfig.setter) {
attrConfig.setter.call(this, val, attr);
} else if (Y_Node.re_aria.test(attr)) { // special case Aria
this._node.setAttribute(attr, val);
} else {
Y_Node.DEFAULT_SETTER.apply(this, arguments);
}
}
return this;
},
/**
* Sets multiple attributes.
* @method setAttrs
* @param {Object} attrMap an object of name/value pairs to set
* @chainable
*/
setAttrs: function(attrMap) {
if (this._setAttrs) { // use Attribute imple
this._setAttrs(attrMap);
} else { // use setters inline
Y.Object.each(attrMap, function(v, n) {
this.set(n, v);
}, this);
}
return this;
},
/**
* Returns an object containing the values for the requested attributes.
* @method getAttrs
* @param {Array} attrs an array of attributes to get values
* @return {Object} An object with attribute name/value pairs.
*/
getAttrs: function(attrs) {
var ret = {};
if (this._getAttrs) { // use Attribute imple
this._getAttrs(attrs);
} else { // use setters inline
Y.Array.each(attrs, function(v, n) {
ret[v] = this.get(v);
}, this);
}
return ret;
},
/**
* Compares nodes to determine if they match.
* Node instances can be compared to each other and/or HTMLElements.
* @method compareTo
* @param {HTMLElement | Node} refNode The reference node to compare to the node.
* @return {Boolean} True if the nodes match, false if they do not.
*/
compareTo: function(refNode) {
var node = this._node;
if (refNode && refNode._node) {
refNode = refNode._node;
}
return node === refNode;
},
/**
* Determines whether the node is appended to the document.
* @method inDoc
* @param {Node|HTMLElement} doc optional An optional document to check against.
* Defaults to current document.
* @return {Boolean} Whether or not this node is appended to the document.
*/
inDoc: function(doc) {
var node = this._node;
doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT];
if (doc.documentElement) {
return Y_DOM.contains(doc.documentElement, node);
}
},
getById: function(id) {
var node = this._node,
ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]);
if (ret && Y_DOM.contains(node, ret)) {
ret = Y.one(ret);
} else {
ret = null;
}
return ret;
},
/**
* Returns the nearest ancestor that passes the test applied by supplied boolean method.
* @method ancestor
* @param {String | Function} fn A selector string or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* @param {String | Function} stopFn optional A selector string or boolean
* method to indicate when the search should stop. The search bails when the function
* returns true or the selector matches.
* If a function is used, it receives the current node being tested as the only argument.
* @return {Node} The matching Node instance or null if not found
*/
ancestor: function(fn, testSelf, stopFn) {
// testSelf is optional, check for stopFn as 2nd arg
if (arguments.length === 2 &&
(typeof testSelf == 'string' || typeof testSelf == 'function')) {
stopFn = testSelf;
}
return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn)));
},
/**
* Returns the ancestors that pass the test applied by supplied boolean method.
* @method ancestors
* @param {String | Function} fn A selector string or boolean method for testing elements.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* If a function is used, it receives the current node being tested as the only argument.
* @return {NodeList} A NodeList instance containing the matching elements
*/
ancestors: function(fn, testSelf, stopFn) {
if (arguments.length === 2 &&
(typeof testSelf == 'string' || typeof testSelf == 'function')) {
stopFn = testSelf;
}
return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn)));
},
/**
* Returns the previous matching sibling.
* Returns the nearest element node sibling if no method provided.
* @method previous
* @param {String | Function} fn A selector or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* @return {Node} Node instance or null if not found
*/
previous: function(fn, all) {
return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all));
},
/**
* Returns the next matching sibling.
* Returns the nearest element node sibling if no method provided.
* @method next
* @param {String | Function} fn A selector or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* @return {Node} Node instance or null if not found
*/
next: function(fn, all) {
return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all));
},
/**
* Returns all matching siblings.
* Returns all siblings if no method provided.
* @method siblings
* @param {String | Function} fn A selector or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* @return {NodeList} NodeList instance bound to found siblings
*/
siblings: function(fn) {
return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn)));
},
/**
* Retrieves a Node instance of nodes based on the given CSS selector.
* @method one
*
* @param {string} selector The CSS selector to test against.
* @return {Node} A Node instance for the matching HTMLElement.
*/
one: function(selector) {
return Y.one(Y.Selector.query(selector, this._node, true));
},
/**
* Retrieves a NodeList based on the given CSS selector.
* @method all
*
* @param {string} selector The CSS selector to test against.
* @return {NodeList} A NodeList instance for the matching HTMLCollection/Array.
*/
all: function(selector) {
var nodelist = Y.all(Y.Selector.query(selector, this._node));
nodelist._query = selector;
nodelist._queryRoot = this._node;
return nodelist;
},
// TODO: allow fn test
/**
* Test if the supplied node matches the supplied selector.
* @method test
*
* @param {string} selector The CSS selector to test against.
* @return {boolean} Whether or not the node matches the selector.
*/
test: function(selector) {
return Y.Selector.test(this._node, selector);
},
/**
* Removes the node from its parent.
* Shortcut for myNode.get('parentNode').removeChild(myNode);
* @method remove
* @param {Boolean} destroy whether or not to call destroy() on the node
* after removal.
* @chainable
*
*/
remove: function(destroy) {
var node = this._node;
if (node && node.parentNode) {
node.parentNode.removeChild(node);
}
if (destroy) {
this.destroy();
}
return this;
},
/**
* Replace the node with the other node. This is a DOM update only
* and does not change the node bound to the Node instance.
* Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode);
* @method replace
* @param {Node | HTMLNode} newNode Node to be inserted
* @chainable
*
*/
replace: function(newNode) {
var node = this._node;
if (typeof newNode == 'string') {
newNode = Y_Node.create(newNode);
}
node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node);
return this;
},
/**
* @method replaceChild
* @for Node
* @param {String | HTMLElement | Node} node Node to be inserted
* @param {HTMLElement | Node} refNode Node to be replaced
* @return {Node} The replaced node
*/
replaceChild: function(node, refNode) {
if (typeof node == 'string') {
node = Y_DOM.create(node);
}
return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode)));
},
/**
* Nulls internal node references, removes any plugins and event listeners
* @method destroy
* @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the
* node's subtree (default is false)
*
*/
destroy: function(recursive) {
var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid',
instance;
this.purge(); // TODO: only remove events add via this Node
if (this.unplug) { // may not be a PluginHost
this.unplug();
}
this.clearData();
if (recursive) {
Y.NodeList.each(this.all('*'), function(node) {
instance = Y_Node._instances[node[UID]];
if (instance) {
instance.destroy();
}
});
}
this._node = null;
this._stateProxy = null;
delete Y_Node._instances[this._yuid];
},
/**
* Invokes a method on the Node instance
* @method invoke
* @param {String} method The name of the method to invoke
* @param {Any} a, b, c, etc. Arguments to invoke the method with.
* @return Whatever the underly method returns.
* DOM Nodes and Collections return values
* are converted to Node/NodeList instances.
*
*/
invoke: function(method, a, b, c, d, e) {
var node = this._node,
ret;
if (a && a._node) {
a = a._node;
}
if (b && b._node) {
b = b._node;
}
ret = node[method](a, b, c, d, e);
return Y_Node.scrubVal(ret, this);
},
/**
* @method swap
* @description Swap DOM locations with the given node.
* This does not change which DOM node each Node instance refers to.
* @param {Node} otherNode The node to swap with
* @chainable
*/
swap: Y.config.doc.documentElement.swapNode ?
function(otherNode) {
this._node.swapNode(Y_Node.getDOMNode(otherNode));
} :
function(otherNode) {
otherNode = Y_Node.getDOMNode(otherNode);
var node = this._node,
parent = otherNode.parentNode,
nextSibling = otherNode.nextSibling;
if (nextSibling === node) {
parent.insertBefore(node, otherNode);
} else if (otherNode === node.nextSibling) {
parent.insertBefore(otherNode, node);
} else {
node.parentNode.replaceChild(otherNode, node);
Y_DOM.addHTML(parent, node, nextSibling);
}
return this;
},
hasMethod: function(method) {
var node = this._node;
return !!(node && method in node &&
typeof node[method] != 'unknown' &&
(typeof node[method] == 'function' ||
String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space
},
isFragment: function() {
return (this.get('nodeType') === 11);
},
/**
* Removes and destroys all of the nodes within the node.
* @method empty
* @chainable
*/
empty: function() {
this.get('childNodes').remove().destroy(true);
return this;
},
/**
* Returns the DOM node bound to the Node instance
* @method getDOMNode
* @return {DOMNode}
*/
getDOMNode: function() {
return this._node;
}
}, true);
Y.Node = Y_Node;
Y.one = Y_Node.one;
/**
* The NodeList module provides support for managing collections of Nodes.
* @module node
* @submodule node-core
*/
/**
* The NodeList class provides a wrapper for manipulating DOM NodeLists.
* NodeList properties can be accessed via the set/get methods.
* Use Y.all() to retrieve NodeList instances.
*
* @class NodeList
* @constructor
*/
var NodeList = function(nodes) {
var tmp = [];
if (nodes) {
if (typeof nodes === 'string') { // selector query
this._query = nodes;
nodes = Y.Selector.query(nodes);
} else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window
nodes = [nodes];
} else if (nodes._node) { // Y.Node
nodes = [nodes._node];
} else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes
Y.Array.each(nodes, function(node) {
if (node._node) {
tmp.push(node._node);
}
});
nodes = tmp;
} else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes)
nodes = Y.Array(nodes, 0, true);
}
}
/**
* The underlying array of DOM nodes bound to the Y.NodeList instance
* @property _nodes
* @private
*/
this._nodes = nodes || [];
};
NodeList.NAME = 'NodeList';
/**
* Retrieves the DOM nodes bound to a NodeList instance
* @method getDOMNodes
* @static
*
* @param {NodeList} nodelist The NodeList instance
* @return {Array} The array of DOM nodes bound to the NodeList
*/
NodeList.getDOMNodes = function(nodelist) {
return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist;
};
NodeList.each = function(instance, fn, context) {
var nodes = instance._nodes;
if (nodes && nodes.length) {
Y.Array.each(nodes, fn, context || instance);
} else {
Y.log('no nodes bound to ' + this, 'warn', 'NodeList');
}
};
NodeList.addMethod = function(name, fn, context) {
if (name && fn) {
NodeList.prototype[name] = function() {
var ret = [],
args = arguments;
Y.Array.each(this._nodes, function(node) {
var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid',
instance = Y.Node._instances[node[UID]],
ctx,
result;
if (!instance) {
instance = NodeList._getTempNode(node);
}
ctx = context || instance;
result = fn.apply(ctx, args);
if (result !== undefined && result !== instance) {
ret[ret.length] = result;
}
});
// TODO: remove tmp pointer
return ret.length ? ret : this;
};
} else {
Y.log('unable to add method: ' + name + ' to NodeList', 'warn', 'node');
}
};
NodeList.importMethod = function(host, name, altName) {
if (typeof name === 'string') {
altName = altName || name;
NodeList.addMethod(name, host[name]);
} else {
Y.Array.each(name, function(n) {
NodeList.importMethod(host, n);
});
}
};
NodeList._getTempNode = function(node) {
var tmp = NodeList._tempNode;
if (!tmp) {
tmp = Y.Node.create('<div></div>');
NodeList._tempNode = tmp;
}
tmp._node = node;
tmp._stateProxy = node;
return tmp;
};
Y.mix(NodeList.prototype, {
_invoke: function(method, args, getter) {
var ret = (getter) ? [] : this;
this.each(function(node) {
var val = node[method].apply(node, args);
if (getter) {
ret.push(val);
}
});
return ret;
},
/**
* Retrieves the Node instance at the given index.
* @method item
*
* @param {Number} index The index of the target Node.
* @return {Node} The Node instance at the given index.
*/
item: function(index) {
return Y.one((this._nodes || [])[index]);
},
/**
* Applies the given function to each Node in the NodeList.
* @method each
* @param {Function} fn The function to apply. It receives 3 arguments:
* the current node instance, the node's index, and the NodeList instance
* @param {Object} context optional An optional context to apply the function with
* Default context is the current Node instance
* @chainable
*/
each: function(fn, context) {
var instance = this;
Y.Array.each(this._nodes, function(node, index) {
node = Y.one(node);
return fn.call(context || node, node, index, instance);
});
return instance;
},
batch: function(fn, context) {
var nodelist = this;
Y.Array.each(this._nodes, function(node, index) {
var instance = Y.Node._instances[node[UID]];
if (!instance) {
instance = NodeList._getTempNode(node);
}
return fn.call(context || instance, instance, index, nodelist);
});
return nodelist;
},
/**
* Executes the function once for each node until a true value is returned.
* @method some
* @param {Function} fn The function to apply. It receives 3 arguments:
* the current node instance, the node's index, and the NodeList instance
* @param {Object} context optional An optional context to execute the function from.
* Default context is the current Node instance
* @return {Boolean} Whether or not the function returned true for any node.
*/
some: function(fn, context) {
var instance = this;
return Y.Array.some(this._nodes, function(node, index) {
node = Y.one(node);
context = context || node;
return fn.call(context, node, index, instance);
});
},
/**
* Creates a documenFragment from the nodes bound to the NodeList instance
* @method toFrag
* @return {Node} a Node instance bound to the documentFragment
*/
toFrag: function() {
return Y.one(Y.DOM._nl2frag(this._nodes));
},
/**
* Returns the index of the node in the NodeList instance
* or -1 if the node isn't found.
* @method indexOf
* @param {Node | DOMNode} node the node to search for
* @return {Int} the index of the node value or -1 if not found
*/
indexOf: function(node) {
return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node));
},
/**
* Filters the NodeList instance down to only nodes matching the given selector.
* @method filter
* @param {String} selector The selector to filter against
* @return {NodeList} NodeList containing the updated collection
* @see Selector
*/
filter: function(selector) {
return Y.all(Y.Selector.filter(this._nodes, selector));
},
/**
* Creates a new NodeList containing all nodes at every n indices, where
* remainder n % index equals r.
* (zero-based index).
* @method modulus
* @param {Int} n The offset to use (return every nth node)
* @param {Int} r An optional remainder to use with the modulus operation (defaults to zero)
* @return {NodeList} NodeList containing the updated collection
*/
modulus: function(n, r) {
r = r || 0;
var nodes = [];
NodeList.each(this, function(node, i) {
if (i % n === r) {
nodes.push(node);
}
});
return Y.all(nodes);
},
/**
* Creates a new NodeList containing all nodes at odd indices
* (zero-based index).
* @method odd
* @return {NodeList} NodeList containing the updated collection
*/
odd: function() {
return this.modulus(2, 1);
},
/**
* Creates a new NodeList containing all nodes at even indices
* (zero-based index), including zero.
* @method even
* @return {NodeList} NodeList containing the updated collection
*/
even: function() {
return this.modulus(2);
},
destructor: function() {
},
/**
* Reruns the initial query, when created using a selector query
* @method refresh
* @chainable
*/
refresh: function() {
var doc,
nodes = this._nodes,
query = this._query,
root = this._queryRoot;
if (query) {
if (!root) {
if (nodes && nodes[0] && nodes[0].ownerDocument) {
root = nodes[0].ownerDocument;
}
}
this._nodes = Y.Selector.query(query, root);
}
return this;
},
/**
* Returns the current number of items in the NodeList.
* @method size
* @return {Int} The number of items in the NodeList.
*/
size: function() {
return this._nodes.length;
},
/**
* Determines if the instance is bound to any nodes
* @method isEmpty
* @return {Boolean} Whether or not the NodeList is bound to any nodes
*/
isEmpty: function() {
return this._nodes.length < 1;
},
toString: function() {
var str = '',
errorMsg = this[UID] + ': not bound to any nodes',
nodes = this._nodes,
node;
if (nodes && nodes[0]) {
node = nodes[0];
str += node[NODE_NAME];
if (node.id) {
str += '#' + node.id;
}
if (node.className) {
str += '.' + node.className.replace(' ', '.');
}
if (nodes.length > 1) {
str += '...[' + nodes.length + ' items]';
}
}
return str || errorMsg;
},
/**
* Returns the DOM node bound to the Node instance
* @method getDOMNodes
* @return {Array}
*/
getDOMNodes: function() {
return this._nodes;
}
}, true);
NodeList.importMethod(Y.Node.prototype, [
/** Called on each Node instance
* @method destroy
* @see Node.destroy
*/
'destroy',
/** Called on each Node instance
* @method empty
* @see Node.empty
*/
'empty',
/** Called on each Node instance
* @method remove
* @see Node.remove
*/
'remove',
/** Called on each Node instance
* @method set
* @see Node.set
*/
'set'
]);
// one-off implementation to convert array of Nodes to NodeList
// e.g. Y.all('input').get('parentNode');
/** Called on each Node instance
* @method get
* @see Node
*/
NodeList.prototype.get = function(attr) {
var ret = [],
nodes = this._nodes,
isNodeList = false,
getTemp = NodeList._getTempNode,
instance,
val;
if (nodes[0]) {
instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]);
val = instance._get(attr);
if (val && val.nodeType) {
isNodeList = true;
}
}
Y.Array.each(nodes, function(node) {
instance = Y.Node._instances[node._yuid];
if (!instance) {
instance = getTemp(node);
}
val = instance._get(attr);
if (!isNodeList) { // convert array of Nodes to NodeList
val = Y.Node.scrubVal(val, instance);
}
ret.push(val);
});
return (isNodeList) ? Y.all(ret) : ret;
};
Y.NodeList = NodeList;
Y.all = function(nodes) {
return new NodeList(nodes);
};
Y.Node.all = Y.all;
/**
* @module node
* @submodule node-core
*/
var Y_NodeList = Y.NodeList,
ArrayProto = Array.prototype,
ArrayMethods = {
/** Returns a new NodeList combining the given NodeList(s)
* @for NodeList
* @method concat
* @param {NodeList | Array} valueN Arrays/NodeLists and/or values to
* concatenate to the resulting NodeList
* @return {NodeList} A new NodeList comprised of this NodeList joined with the input.
*/
'concat': 1,
/** Removes the last from the NodeList and returns it.
* @for NodeList
* @method pop
* @return {Node} The last item in the NodeList.
*/
'pop': 0,
/** Adds the given Node(s) to the end of the NodeList.
* @for NodeList
* @method push
* @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList.
*/
'push': 0,
/** Removes the first item from the NodeList and returns it.
* @for NodeList
* @method shift
* @return {Node} The first item in the NodeList.
*/
'shift': 0,
/** Returns a new NodeList comprising the Nodes in the given range.
* @for NodeList
* @method slice
* @param {Number} begin Zero-based index at which to begin extraction.
As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence.
* @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end.
slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).
As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.
If end is omitted, slice extracts to the end of the sequence.
* @return {NodeList} A new NodeList comprised of this NodeList joined with the input.
*/
'slice': 1,
/** Changes the content of the NodeList, adding new elements while removing old elements.
* @for NodeList
* @method splice
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end.
* @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed.
* {Node | DOMNode| element1, ..., elementN
The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array.
* @return {NodeList} The element(s) removed.
*/
'splice': 1,
/** Adds the given Node(s) to the beginning of the NodeList.
* @for NodeList
* @method unshift
* @param {Node | DOMNode} nodes One or more nodes to add to the NodeList.
*/
'unshift': 0
};
Y.Object.each(ArrayMethods, function(returnNodeList, name) {
Y_NodeList.prototype[name] = function() {
var args = [],
i = 0,
arg,
ret;
while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists
args.push(arg._node || arg._nodes || arg);
}
ret = ArrayProto[name].apply(this._nodes, args);
if (returnNodeList) {
ret = Y.all(ret);
} else {
ret = Y.Node.scrubVal(ret);
}
return ret;
};
});
/**
* @module node
* @submodule node-core
*/
Y.Array.each([
/**
* Passes through to DOM method.
* @for Node
* @method removeChild
* @param {HTMLElement | Node} node Node to be removed
* @return {Node} The removed node
*/
'removeChild',
/**
* Passes through to DOM method.
* @method hasChildNodes
* @return {Boolean} Whether or not the node has any childNodes
*/
'hasChildNodes',
/**
* Passes through to DOM method.
* @method cloneNode
* @param {Boolean} deep Whether or not to perform a deep clone, which includes
* subtree and attributes
* @return {Node} The clone
*/
'cloneNode',
/**
* Passes through to DOM method.
* @method hasAttribute
* @param {String} attribute The attribute to test for
* @return {Boolean} Whether or not the attribute is present
*/
'hasAttribute',
/**
* Passes through to DOM method.
* @method scrollIntoView
* @chainable
*/
'scrollIntoView',
/**
* Passes through to DOM method.
* @method getElementsByTagName
* @param {String} tagName The tagName to collect
* @return {NodeList} A NodeList representing the HTMLCollection
*/
'getElementsByTagName',
/**
* Passes through to DOM method.
* @method focus
* @chainable
*/
'focus',
/**
* Passes through to DOM method.
* @method blur
* @chainable
*/
'blur',
/**
* Passes through to DOM method.
* Only valid on FORM elements
* @method submit
* @chainable
*/
'submit',
/**
* Passes through to DOM method.
* Only valid on FORM elements
* @method reset
* @chainable
*/
'reset',
/**
* Passes through to DOM method.
* @method select
* @chainable
*/
'select',
/**
* Passes through to DOM method.
* Only valid on TABLE elements
* @method createCaption
* @chainable
*/
'createCaption'
], function(method) {
Y.log('adding: ' + method, 'info', 'node');
Y.Node.prototype[method] = function(arg1, arg2, arg3) {
var ret = this.invoke(method, arg1, arg2, arg3);
return ret;
};
});
/**
* Passes through to DOM method.
* @method removeAttribute
* @param {String} attribute The attribute to be removed
* @chainable
*/
// one-off implementation due to IE returning boolean, breaking chaining
Y.Node.prototype.removeAttribute = function(attr) {
var node = this._node;
if (node) {
node.removeAttribute(attr);
}
return this;
};
Y.Node.importMethod(Y.DOM, [
/**
* Determines whether the node is an ancestor of another HTML element in the DOM hierarchy.
* @method contains
* @param {Node | HTMLElement} needle The possible node or descendent
* @return {Boolean} Whether or not this node is the needle its ancestor
*/
'contains',
/**
* Allows setting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method setAttribute
* @for Node
* @chainable
* @param {string} name The attribute name
* @param {string} value The value to set
*/
'setAttribute',
/**
* Allows getting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method getAttribute
* @for Node
* @param {string} name The attribute name
* @return {string} The attribute value
*/
'getAttribute',
/**
* Wraps the given HTML around the node.
* @method wrap
* @param {String} html The markup to wrap around the node.
* @chainable
* @for Node
*/
'wrap',
/**
* Removes the node's parent node.
* @method unwrap
* @chainable
*/
'unwrap',
/**
* Applies a unique ID to the node if none exists
* @method generateID
* @return {String} The existing or generated ID
*/
'generateID'
]);
Y.NodeList.importMethod(Y.Node.prototype, [
/**
* Allows getting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method getAttribute
* @see Node
* @for NodeList
* @param {string} name The attribute name
* @return {string} The attribute value
*/
'getAttribute',
/**
* Allows setting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method setAttribute
* @see Node
* @for NodeList
* @chainable
* @param {string} name The attribute name
* @param {string} value The value to set
*/
'setAttribute',
/**
* Allows for removing attributes on DOM nodes.
* This passes through to the DOM node, allowing for custom attributes.
* @method removeAttribute
* @see Node
* @for NodeList
* @param {string} name The attribute to remove
*/
'removeAttribute',
/**
* Removes the parent node from node in the list.
* @method unwrap
* @chainable
*/
'unwrap',
/**
* Wraps the given HTML around each node.
* @method wrap
* @param {String} html The markup to wrap around the node.
* @chainable
*/
'wrap',
/**
* Applies a unique ID to each node if none exists
* @method generateID
* @return {String} The existing or generated ID
*/
'generateID'
]);
}, '@VERSION@' ,{requires:['dom-core', 'selector']});
YUI.add('node-base', function(Y) {
/**
* @module node
* @submodule node-base
*/
var methods = [
/**
* Determines whether each node has the given className.
* @method hasClass
* @for Node
* @param {String} className the class name to search for
* @return {Boolean} Whether or not the element has the specified class
*/
'hasClass',
/**
* Adds a class name to each node.
* @method addClass
* @param {String} className the class name to add to the node's class attribute
* @chainable
*/
'addClass',
/**
* Removes a class name from each node.
* @method removeClass
* @param {String} className the class name to remove from the node's class attribute
* @chainable
*/
'removeClass',
/**
* Replace a class with another class for each node.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
* @chainable
*/
'replaceClass',
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @param {String} className the class name to be toggled
* @param {Boolean} force Option to force adding or removing the class.
* @chainable
*/
'toggleClass'
];
Y.Node.importMethod(Y.DOM, methods);
/**
* Determines whether each node has the given className.
* @method hasClass
* @see Node.hasClass
* @for NodeList
* @param {String} className the class name to search for
* @return {Array} An array of booleans for each node bound to the NodeList.
*/
/**
* Adds a class name to each node.
* @method addClass
* @see Node.addClass
* @param {String} className the class name to add to the node's class attribute
* @chainable
*/
/**
* Removes a class name from each node.
* @method removeClass
* @see Node.removeClass
* @param {String} className the class name to remove from the node's class attribute
* @chainable
*/
/**
* Replace a class with another class for each node.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @see Node.replaceClass
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
* @chainable
*/
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @see Node.toggleClass
* @param {String} className the class name to be toggled
* @chainable
*/
Y.NodeList.importMethod(Y.Node.prototype, methods);
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node,
Y_DOM = Y.DOM;
/**
* Returns a new dom node using the provided markup string.
* @method create
* @static
* @param {String} html The markup used to create the element
* @param {HTMLDocument} doc An optional document context
* @return {Node} A Node instance bound to a DOM node or fragment
* @for Node
*/
Y_Node.create = function(html, doc) {
if (doc && doc._node) {
doc = doc._node;
}
return Y.one(Y_DOM.create(html, doc));
};
Y.mix(Y_Node.prototype, {
/**
* Creates a new Node using the provided markup string.
* @method create
* @param {String} html The markup used to create the element
* @param {HTMLDocument} doc An optional document context
* @return {Node} A Node instance bound to a DOM node or fragment
*/
create: Y_Node.create,
/**
* Inserts the content before the reference node.
* @method insert
* @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert
* @param {Int | Node | HTMLElement | String} where The position to insert at.
* Possible "where" arguments
* <dl>
* <dt>Y.Node</dt>
* <dd>The Node to insert before</dd>
* <dt>HTMLElement</dt>
* <dd>The element to insert before</dd>
* <dt>Int</dt>
* <dd>The index of the child element to insert before</dd>
* <dt>"replace"</dt>
* <dd>Replaces the existing HTML</dd>
* <dt>"before"</dt>
* <dd>Inserts before the existing HTML</dd>
* <dt>"before"</dt>
* <dd>Inserts content before the node</dd>
* <dt>"after"</dt>
* <dd>Inserts content after the node</dd>
* </dl>
* @chainable
*/
insert: function(content, where) {
this._insert(content, where);
return this;
},
_insert: function(content, where) {
var node = this._node,
ret = null;
if (typeof where == 'number') { // allow index
where = this._node.childNodes[where];
} else if (where && where._node) { // Node
where = where._node;
}
if (content && typeof content != 'string') { // allow Node or NodeList/Array instances
content = content._node || content._nodes || content;
}
ret = Y_DOM.addHTML(node, content, where);
return ret;
},
/**
* Inserts the content as the firstChild of the node.
* @method prepend
* @param {String | Node | HTMLElement} content The content to insert
* @chainable
*/
prepend: function(content) {
return this.insert(content, 0);
},
/**
* Inserts the content as the lastChild of the node.
* @method append
* @param {String | Node | HTMLElement} content The content to insert
* @chainable
*/
append: function(content) {
return this.insert(content, null);
},
/**
* @method appendChild
* @param {String | HTMLElement | Node} node Node to be appended
* @return {Node} The appended node
*/
appendChild: function(node) {
return Y_Node.scrubVal(this._insert(node));
},
/**
* @method insertBefore
* @param {String | HTMLElement | Node} newNode Node to be appended
* @param {HTMLElement | Node} refNode Node to be inserted before
* @return {Node} The inserted node
*/
insertBefore: function(newNode, refNode) {
return Y.Node.scrubVal(this._insert(newNode, refNode));
},
/**
* Appends the node to the given node.
* @method appendTo
* @param {Node | HTMLElement} node The node to append to
* @chainable
*/
appendTo: function(node) {
Y.one(node).append(this);
return this;
},
/**
* Replaces the node's current content with the content.
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text.
* @method setContent
* @deprecated Use setHTML
* @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert
* @chainable
*/
setContent: function(content) {
this._insert(content, 'replace');
return this;
},
/**
* Returns the node's current content (e.g. innerHTML)
* @method getContent
* @deprecated Use getHTML
* @return {String} The current content
*/
getContent: function(content) {
return this.get('innerHTML');
}
});
/**
* Replaces the node's current html content with the content provided.
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text.
* @method setHTML
* @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert
* @chainable
*/
Y.Node.prototype.setHTML = Y.Node.prototype.setContent;
/**
* Returns the node's current html content (e.g. innerHTML)
* @method getHTML
* @return {String} The html content
*/
Y.Node.prototype.getHTML = Y.Node.prototype.getContent;
Y.NodeList.importMethod(Y.Node.prototype, [
/**
* Called on each Node instance
* @for NodeList
* @method append
* @see Node.append
*/
'append',
/** Called on each Node instance
* @method insert
* @see Node.insert
*/
'insert',
/**
* Called on each Node instance
* @for NodeList
* @method appendChild
* @see Node.appendChild
*/
'appendChild',
/** Called on each Node instance
* @method insertBefore
* @see Node.insertBefore
*/
'insertBefore',
/** Called on each Node instance
* @method prepend
* @see Node.prepend
*/
'prepend',
/** Called on each Node instance
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text.
* @method setContent
* @deprecated Use setHTML
*/
'setContent',
/** Called on each Node instance
* @method getContent
* @deprecated Use getHTML
*/
'getContent',
/** Called on each Node instance
* @method setHTML
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text.
*/
'setHTML',
/** Called on each Node instance
* @method getHTML
*/
'getHTML'
]);
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node,
Y_DOM = Y.DOM;
/**
* Static collection of configuration attributes for special handling
* @property ATTRS
* @static
* @type object
*/
Y_Node.ATTRS = {
/**
* Allows for getting and setting the text of an element.
* Formatting is preserved and special characters are treated literally.
* @config text
* @type String
*/
text: {
getter: function() {
return Y_DOM.getText(this._node);
},
setter: function(content) {
Y_DOM.setText(this._node, content);
return content;
}
},
/**
* Allows for getting and setting the text of an element.
* Formatting is preserved and special characters are treated literally.
* @config for
* @type String
*/
'for': {
getter: function() {
return Y_DOM.getAttribute(this._node, 'for');
},
setter: function(val) {
Y_DOM.setAttribute(this._node, 'for', val);
return val;
}
},
'options': {
getter: function() {
return this._node.getElementsByTagName('option');
}
},
/**
* Returns a NodeList instance of all HTMLElement children.
* @readOnly
* @config children
* @type NodeList
*/
'children': {
getter: function() {
var node = this._node,
children = node.children,
childNodes, i, len;
if (!children) {
childNodes = node.childNodes;
children = [];
for (i = 0, len = childNodes.length; i < len; ++i) {
if (childNodes[i].tagName) {
children[children.length] = childNodes[i];
}
}
}
return Y.all(children);
}
},
value: {
getter: function() {
return Y_DOM.getValue(this._node);
},
setter: function(val) {
Y_DOM.setValue(this._node, val);
return val;
}
}
};
Y.Node.importMethod(Y.DOM, [
/**
* Allows setting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method setAttribute
* @for Node
* @for NodeList
* @chainable
* @param {string} name The attribute name
* @param {string} value The value to set
*/
'setAttribute',
/**
* Allows getting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method getAttribute
* @for Node
* @for NodeList
* @param {string} name The attribute name
* @return {string} The attribute value
*/
'getAttribute'
]);
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node;
var Y_NodeList = Y.NodeList;
/**
* List of events that route to DOM events
* @static
* @property DOM_EVENTS
* @for Node
*/
Y_Node.DOM_EVENTS = {
abort: 1,
beforeunload: 1,
blur: 1,
change: 1,
click: 1,
close: 1,
command: 1,
contextmenu: 1,
dblclick: 1,
DOMMouseScroll: 1,
drag: 1,
dragstart: 1,
dragenter: 1,
dragover: 1,
dragleave: 1,
dragend: 1,
drop: 1,
error: 1,
focus: 1,
key: 1,
keydown: 1,
keypress: 1,
keyup: 1,
load: 1,
message: 1,
mousedown: 1,
mouseenter: 1,
mouseleave: 1,
mousemove: 1,
mousemultiwheel: 1,
mouseout: 1,
mouseover: 1,
mouseup: 1,
mousewheel: 1,
orientationchange: 1,
reset: 1,
resize: 1,
select: 1,
selectstart: 1,
submit: 1,
scroll: 1,
textInput: 1,
unload: 1
};
// Add custom event adaptors to this list. This will make it so
// that delegate, key, available, contentready, etc all will
// be available through Node.on
Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins);
Y.augment(Y_Node, Y.EventTarget);
Y.mix(Y_Node.prototype, {
/**
* Removes event listeners from the node and (optionally) its subtree
* @method purge
* @param {Boolean} recurse (optional) Whether or not to remove listeners from the
* node's subtree
* @param {String} type (optional) Only remove listeners of the specified type
* @chainable
*
*/
purge: function(recurse, type) {
Y.Event.purgeElement(this._node, recurse, type);
return this;
}
});
Y.mix(Y.NodeList.prototype, {
_prepEvtArgs: function(type, fn, context) {
// map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc)
var args = Y.Array(arguments, 0, true);
if (args.length < 2) { // type only (event hash) just add nodes
args[2] = this._nodes;
} else {
args.splice(2, 0, this._nodes);
}
args[3] = context || this; // default to NodeList instance as context
return args;
},
/**
Subscribe a callback function for each `Node` in the collection to execute
in response to a DOM event.
NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in
favor of using event delegation from a parent Node. See the Event user
guide for details.
Most DOM events are associated with a preventable default behavior, such as
link clicks navigating to a new page. Callbacks are passed a
`DOMEventFacade` object as their first argument (usually called `e`) that
can be used to prevent this default behavior with `e.preventDefault()`. See
the `DOMEventFacade` API for all available properties and methods on the
object.
By default, the `this` object will be the `NodeList` that the subscription
came from, <em>not the `Node` that received the event</em>. Use
`e.currentTarget` to refer to the `Node`.
Returning `false` from a callback is supported as an alternative to calling
`e.preventDefault(); e.stopPropagation();`. However, it is recommended to
use the event methods.
@example
Y.all(".sku").on("keydown", function (e) {
if (e.keyCode === 13) {
e.preventDefault();
// Use e.currentTarget to refer to the individual Node
var item = Y.MyApp.searchInventory( e.currentTarget.get('value') );
// etc ...
}
});
@method on
@param {String} type The name of the event
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching that
subscription
@for NodeList
**/
on: function(type, fn, context) {
return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments));
},
/**
* Applies an one-time event listener to each Node bound to the NodeList.
* @method once
* @param {String} type The event being listened for
* @param {Function} fn The handler to call when the event fires
* @param {Object} context The context to call the handler with.
* Default is the NodeList instance.
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
* @for NodeList
*/
once: function(type, fn, context) {
return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments));
},
/**
* Applies an event listener to each Node bound to the NodeList.
* The handler is called only after all on() handlers are called
* and the event is not prevented.
* @method after
* @param {String} type The event being listened for
* @param {Function} fn The handler to call when the event fires
* @param {Object} context The context to call the handler with.
* Default is the NodeList instance.
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
* @for NodeList
*/
after: function(type, fn, context) {
return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments));
},
/**
* Applies an one-time event listener to each Node bound to the NodeList
* that will be called only after all on() handlers are called and the
* event is not prevented.
*
* @method onceAfter
* @param {String} type The event being listened for
* @param {Function} fn The handler to call when the event fires
* @param {Object} context The context to call the handler with.
* Default is the NodeList instance.
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
* @for NodeList
*/
onceAfter: function(type, fn, context) {
return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments));
}
});
Y_NodeList.importMethod(Y.Node.prototype, [
/**
* Called on each Node instance
* @method detach
* @see Node.detach
* @for NodeList
*/
'detach',
/** Called on each Node instance
* @method detachAll
* @see Node.detachAll
* @for NodeList
*/
'detachAll'
]);
/**
Subscribe a callback function to execute in response to a DOM event or custom
event.
Most DOM events are associated with a preventable default behavior such as
link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade`
object as their first argument (usually called `e`) that can be used to
prevent this default behavior with `e.preventDefault()`. See the
`DOMEventFacade` API for all available properties and methods on the object.
If the event name passed as the first parameter is not a whitelisted DOM event,
it will be treated as a custom event subscriptions, allowing
`node.fire('customEventName')` later in the code. Refer to the Event user guide
for the full DOM event whitelist.
By default, the `this` object in the callback will refer to the subscribed
`Node`.
Returning `false` from a callback is supported as an alternative to calling
`e.preventDefault(); e.stopPropagation();`. However, it is recommended to use
the event methods.
@example
Y.one("#my-form").on("submit", function (e) {
e.preventDefault();
// proceed with ajax form submission instead...
});
@method on
@param {String} type The name of the event
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching that
subscription
@for Node
**/
Y.mix(Y.Node.ATTRS, {
offsetHeight: {
setter: function(h) {
Y.DOM.setHeight(this._node, h);
return h;
},
getter: function() {
return this._node.offsetHeight;
}
},
offsetWidth: {
setter: function(w) {
Y.DOM.setWidth(this._node, w);
return w;
},
getter: function() {
return this._node.offsetWidth;
}
}
});
Y.mix(Y.Node.prototype, {
sizeTo: function(w, h) {
var node;
if (arguments.length < 2) {
node = Y.one(w);
w = node.get('offsetWidth');
h = node.get('offsetHeight');
}
this.setAttrs({
offsetWidth: w,
offsetHeight: h
});
}
});
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node;
Y.mix(Y_Node.prototype, {
/**
* Makes the node visible.
* If the "transition" module is loaded, show optionally
* animates the showing of the node using either the default
* transition effect ('fadeIn'), or the given named effect.
* @method show
* @for Node
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @chainable
*/
show: function(callback) {
callback = arguments[arguments.length - 1];
this.toggleView(true, callback);
return this;
},
/**
* The implementation for showing nodes.
* Default is to toggle the style.display property.
* @method _show
* @protected
* @chainable
*/
_show: function() {
this.setStyle('display', '');
},
_isHidden: function() {
return Y.DOM.getStyle(this._node, 'display') === 'none';
},
/**
* Displays or hides the node.
* If the "transition" module is loaded, toggleView optionally
* animates the toggling of the node using either the default
* transition effect ('fadeIn'), or the given named effect.
* @method toggleView
* @for Node
* @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden
* @param {Function} [callback] An optional function to run after the transition completes.
* @chainable
*/
toggleView: function(on, callback) {
this._toggleView.apply(this, arguments);
return this;
},
_toggleView: function(on, callback) {
callback = arguments[arguments.length - 1];
// base on current state if not forcing
if (typeof on != 'boolean') {
on = (this._isHidden()) ? 1 : 0;
}
if (on) {
this._show();
} else {
this._hide();
}
if (typeof callback == 'function') {
callback.call(this);
}
return this;
},
/**
* Hides the node.
* If the "transition" module is loaded, hide optionally
* animates the hiding of the node using either the default
* transition effect ('fadeOut'), or the given named effect.
* @method hide
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @chainable
*/
hide: function(callback) {
callback = arguments[arguments.length - 1];
this.toggleView(false, callback);
return this;
},
/**
* The implementation for hiding nodes.
* Default is to toggle the style.display property.
* @method _hide
* @protected
* @chainable
*/
_hide: function() {
this.setStyle('display', 'none');
}
});
Y.NodeList.importMethod(Y.Node.prototype, [
/**
* Makes each node visible.
* If the "transition" module is loaded, show optionally
* animates the showing of the node using either the default
* transition effect ('fadeIn'), or the given named effect.
* @method show
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @for NodeList
* @chainable
*/
'show',
/**
* Hides each node.
* If the "transition" module is loaded, hide optionally
* animates the hiding of the node using either the default
* transition effect ('fadeOut'), or the given named effect.
* @method hide
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @chainable
*/
'hide',
/**
* Displays or hides each node.
* If the "transition" module is loaded, toggleView optionally
* animates the toggling of the nodes using either the default
* transition effect ('fadeIn'), or the given named effect.
* @method toggleView
* @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden
* @param {Function} [callback] An optional function to run after the transition completes.
* @chainable
*/
'toggleView'
]);
if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8
Y.Node.prototype.hasAttribute = function(attr) {
if (attr === 'value') {
if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML
return true;
}
}
return !!(this._node.attributes[attr] &&
this._node.attributes[attr].specified);
};
}
// IE throws an error when calling focus() on an element that's invisible, not
// displayed, or disabled.
Y.Node.prototype.focus = function () {
try {
this._node.focus();
} catch (e) {
Y.log('error focusing node: ' + e.toString(), 'error', 'node');
}
return this;
};
// IE throws error when setting input.type = 'hidden',
// input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden'
Y.Node.ATTRS.type = {
setter: function(val) {
if (val === 'hidden') {
try {
this._node.type = 'hidden';
} catch(e) {
this.setStyle('display', 'none');
this._inputType = 'hidden';
}
} else {
try { // IE errors when changing the type from "hidden'
this._node.type = val;
} catch (e) {
Y.log('error setting type: ' + val, 'info', 'node');
}
}
return val;
},
getter: function() {
return this._inputType || this._node.type;
},
_bypassProxy: true // don't update DOM when using with Attribute
};
if (Y.config.doc.createElement('form').elements.nodeType) {
// IE: elements collection is also FORM node which trips up scrubVal.
Y.Node.ATTRS.elements = {
getter: function() {
return this.all('input, textarea, button, select');
}
};
}
/**
* Provides methods for managing custom Node data.
*
* @module node
* @main node
* @submodule node-data
*/
Y.mix(Y.Node.prototype, {
_initData: function() {
if (! ('_data' in this)) {
this._data = {};
}
},
/**
* @method getData
* @description Retrieves arbitrary data stored on a Node instance.
* If no data is associated with the Node, it will attempt to retrieve
* a value from the corresponding HTML data attribute. (e.g. node.getData('foo')
* will check node.getAttribute('data-foo')).
* @param {string} name Optional name of the data field to retrieve.
* If no name is given, all data is returned.
* @return {any | Object} Whatever is stored at the given field,
* or an object hash of all fields.
*/
getData: function(name) {
this._initData();
var data = this._data,
ret = data;
if (arguments.length) { // single field
if (name in data) {
ret = data[name];
} else { // initialize from HTML attribute
ret = this._getDataAttribute(name);
}
} else if (typeof data == 'object' && data !== null) { // all fields
ret = {};
Y.Object.each(data, function(v, n) {
ret[n] = v;
});
ret = this._getDataAttributes(ret);
}
return ret;
},
_getDataAttributes: function(ret) {
ret = ret || {};
var i = 0,
attrs = this._node.attributes,
len = attrs.length,
prefix = this.DATA_PREFIX,
prefixLength = prefix.length,
name;
while (i < len) {
name = attrs[i].name;
if (name.indexOf(prefix) === 0) {
name = name.substr(prefixLength);
if (!(name in ret)) { // only merge if not already stored
ret[name] = this._getDataAttribute(name);
}
}
i += 1;
}
return ret;
},
_getDataAttribute: function(name) {
var name = this.DATA_PREFIX + name,
node = this._node,
attrs = node.attributes,
data = attrs && attrs[name] && attrs[name].value;
return data;
},
/**
* @method setData
* @description Stores arbitrary data on a Node instance.
* This is not stored with the DOM node.
* @param {string} name The name of the field to set. If no name
* is given, name is treated as the data and overrides any existing data.
* @param {any} val The value to be assigned to the field.
* @chainable
*/
setData: function(name, val) {
this._initData();
if (arguments.length > 1) {
this._data[name] = val;
} else {
this._data = name;
}
return this;
},
/**
* @method clearData
* @description Clears internally stored data.
* @param {string} name The name of the field to clear. If no name
* is given, all data is cleared.
* @chainable
*/
clearData: function(name) {
if ('_data' in this) {
if (typeof name != 'undefined') {
delete this._data[name];
} else {
delete this._data;
}
}
return this;
}
});
Y.mix(Y.NodeList.prototype, {
/**
* @method getData
* @description Retrieves arbitrary data stored on each Node instance
* bound to the NodeList.
* @see Node
* @param {string} name Optional name of the data field to retrieve.
* If no name is given, all data is returned.
* @return {Array} An array containing all of the data for each Node instance.
* or an object hash of all fields.
*/
getData: function(name) {
var args = (arguments.length) ? [name] : [];
return this._invoke('getData', args, true);
},
/**
* @method setData
* @description Stores arbitrary data on each Node instance bound to the
* NodeList. This is not stored with the DOM node.
* @param {string} name The name of the field to set. If no name
* is given, name is treated as the data and overrides any existing data.
* @param {any} val The value to be assigned to the field.
* @chainable
*/
setData: function(name, val) {
var args = (arguments.length > 1) ? [name, val] : [name];
return this._invoke('setData', args);
},
/**
* @method clearData
* @description Clears data on all Node instances bound to the NodeList.
* @param {string} name The name of the field to clear. If no name
* is given, all data is cleared.
* @chainable
*/
clearData: function(name) {
var args = (arguments.length) ? [name] : [];
return this._invoke('clearData', [name]);
}
});
}, '@VERSION@' ,{requires:['dom-base', 'node-core', 'event-base']});
(function () {
var GLOBAL_ENV = YUI.Env;
if (!GLOBAL_ENV._ready) {
GLOBAL_ENV._ready = function() {
GLOBAL_ENV.DOMReady = true;
GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready);
};
GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready);
}
})();
YUI.add('event-base', function(Y) {
/*
* DOM event listener abstraction layer
* @module event
* @submodule event-base
*/
/**
* The domready event fires at the moment the browser's DOM is
* usable. In most cases, this is before images are fully
* downloaded, allowing you to provide a more responsive user
* interface.
*
* In YUI 3, domready subscribers will be notified immediately if
* that moment has already passed when the subscription is created.
*
* One exception is if the yui.js file is dynamically injected into
* the page. If this is done, you must tell the YUI instance that
* you did this in order for DOMReady (and window load events) to
* fire normally. That configuration option is 'injected' -- set
* it to true if the yui.js script is not included inline.
*
* This method is part of the 'event-ready' module, which is a
* submodule of 'event'.
*
* @event domready
* @for YUI
*/
Y.publish('domready', {
fireOnce: true,
async: true
});
if (YUI.Env.DOMReady) {
Y.fire('domready');
} else {
Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready');
}
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event
* @submodule event-base
*/
/**
* Wraps a DOM event, properties requiring browser abstraction are
* fixed here. Provids a security layer when required.
* @class DOMEventFacade
* @param ev {Event} the DOM event
* @param currentTarget {HTMLElement} the element the listener was attached to
* @param wrapper {Event.Custom} the custom event wrapper for this DOM event
*/
var ua = Y.UA,
EMPTY = {},
/**
* webkit key remapping required for Safari < 3.1
* @property webkitKeymap
* @private
*/
webkitKeymap = {
63232: 38, // up
63233: 40, // down
63234: 37, // left
63235: 39, // right
63276: 33, // page up
63277: 34, // page down
25: 9, // SHIFT-TAB (Safari provides a different key code in
// this case, even though the shiftKey modifier is set)
63272: 46, // delete
63273: 36, // home
63275: 35 // end
},
/**
* Returns a wrapped node. Intended to be used on event targets,
* so it will return the node's parent if the target is a text
* node.
*
* If accessing a property of the node throws an error, this is
* probably the anonymous div wrapper Gecko adds inside text
* nodes. This likely will only occur when attempting to access
* the relatedTarget. In this case, we now return null because
* the anonymous div is completely useless and we do not know
* what the related target was because we can't even get to
* the element's parent node.
*
* @method resolve
* @private
*/
resolve = function(n) {
if (!n) {
return n;
}
try {
if (n && 3 == n.nodeType) {
n = n.parentNode;
}
} catch(e) {
return null;
}
return Y.one(n);
},
DOMEventFacade = function(ev, currentTarget, wrapper) {
this._event = ev;
this._currentTarget = currentTarget;
this._wrapper = wrapper || EMPTY;
// if not lazy init
this.init();
};
Y.extend(DOMEventFacade, Object, {
init: function() {
var e = this._event,
overrides = this._wrapper.overrides,
x = e.pageX,
y = e.pageY,
c,
currentTarget = this._currentTarget;
this.altKey = e.altKey;
this.ctrlKey = e.ctrlKey;
this.metaKey = e.metaKey;
this.shiftKey = e.shiftKey;
this.type = (overrides && overrides.type) || e.type;
this.clientX = e.clientX;
this.clientY = e.clientY;
this.pageX = x;
this.pageY = y;
// charCode is unknown in keyup, keydown. keyCode is unknown in keypress.
// FF 3.6 - 8+? pass 0 for keyCode in keypress events.
// Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup.
// Webkit and IE9+? duplicate charCode in keyCode.
// Opera never sets charCode, always keyCode (though with the charCode).
// IE6-8 don't set charCode or which.
// All browsers other than IE6-8 set which=keyCode in keydown, keyup, and
// which=charCode in keypress.
//
// Moral of the story: (e.which || e.keyCode) will always return the
// known code for that key event phase. e.keyCode is often different in
// keypress from keydown and keyup.
c = e.keyCode || e.charCode;
if (ua.webkit && (c in webkitKeymap)) {
c = webkitKeymap[c];
}
this.keyCode = c;
this.charCode = c;
// Fill in e.which for IE - implementers should always use this over
// e.keyCode or e.charCode.
this.which = e.which || e.charCode || c;
// this.button = e.button;
this.button = this.which;
this.target = resolve(e.target);
this.currentTarget = resolve(currentTarget);
this.relatedTarget = resolve(e.relatedTarget);
if (e.type == "mousewheel" || e.type == "DOMMouseScroll") {
this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1);
}
if (this._touch) {
this._touch(e, currentTarget, this._wrapper);
}
},
stopPropagation: function() {
this._event.stopPropagation();
this._wrapper.stopped = 1;
this.stopped = 1;
},
stopImmediatePropagation: function() {
var e = this._event;
if (e.stopImmediatePropagation) {
e.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this._wrapper.stopped = 2;
this.stopped = 2;
},
preventDefault: function(returnValue) {
var e = this._event;
e.preventDefault();
e.returnValue = returnValue || false;
this._wrapper.prevented = 1;
this.prevented = 1;
},
halt: function(immediate) {
if (immediate) {
this.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this.preventDefault();
}
});
DOMEventFacade.resolve = resolve;
Y.DOM2EventFacade = DOMEventFacade;
Y.DOMEventFacade = DOMEventFacade;
/**
* The native event
* @property _event
* @type {Native DOM Event}
* @private
*/
/**
The name of the event (e.g. "click")
@property type
@type {String}
**/
/**
`true` if the "alt" or "option" key is pressed.
@property altKey
@type {Boolean}
**/
/**
`true` if the shift key is pressed.
@property shiftKey
@type {Boolean}
**/
/**
`true` if the "Windows" key on a Windows keyboard, "command" key on an
Apple keyboard, or "meta" key on other keyboards is pressed.
@property metaKey
@type {Boolean}
**/
/**
`true` if the "Ctrl" or "control" key is pressed.
@property ctrlKey
@type {Boolean}
**/
/**
* The X location of the event on the page (including scroll)
* @property pageX
* @type {Number}
*/
/**
* The Y location of the event on the page (including scroll)
* @property pageY
* @type {Number}
*/
/**
* The X location of the event in the viewport
* @property clientX
* @type {Number}
*/
/**
* The Y location of the event in the viewport
* @property clientY
* @type {Number}
*/
/**
* The keyCode for key events. Uses charCode if keyCode is not available
* @property keyCode
* @type {Number}
*/
/**
* The charCode for key events. Same as keyCode
* @property charCode
* @type {Number}
*/
/**
* The button that was pushed. 1 for left click, 2 for middle click, 3 for
* right click. This is only reliably populated on `mouseup` events.
* @property button
* @type {Number}
*/
/**
* The button that was pushed. Same as button.
* @property which
* @type {Number}
*/
/**
* Node reference for the targeted element
* @property target
* @type {Node}
*/
/**
* Node reference for the element that the listener was attached to.
* @property currentTarget
* @type {Node}
*/
/**
* Node reference to the relatedTarget
* @property relatedTarget
* @type {Node}
*/
/**
* Number representing the direction and velocity of the movement of the mousewheel.
* Negative is down, the higher the number, the faster. Applies to the mousewheel event.
* @property wheelDelta
* @type {Number}
*/
/**
* Stops the propagation to the next bubble target
* @method stopPropagation
*/
/**
* Stops the propagation to the next bubble target and
* prevents any additional listeners from being exectued
* on the current target.
* @method stopImmediatePropagation
*/
/**
* Prevents the event's default behavior
* @method preventDefault
* @param returnValue {string} sets the returnValue of the event to this value
* (rather than the default false value). This can be used to add a customized
* confirmation query to the beforeunload event).
*/
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
(function() {
/**
* The event utility provides functions to add and remove event listeners,
* event cleansing. It also tries to automatically remove listeners it
* registers during the unload event.
* @module event
* @main event
* @submodule event-base
*/
/**
* The event utility provides functions to add and remove event listeners,
* event cleansing. It also tries to automatically remove listeners it
* registers during the unload event.
*
* @class Event
* @static
*/
Y.Env.evt.dom_wrappers = {};
Y.Env.evt.dom_map = {};
var _eventenv = Y.Env.evt,
config = Y.config,
win = config.win,
add = YUI.Env.add,
remove = YUI.Env.remove,
onLoad = function() {
YUI.Env.windowLoaded = true;
Y.Event._load();
remove(win, "load", onLoad);
},
onUnload = function() {
Y.Event._unload();
},
EVENT_READY = 'domready',
COMPAT_ARG = '~yui|2|compat~',
shouldIterate = function(o) {
try {
return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) &&
!o.tagName && !o.alert);
} catch(ex) {
Y.log("collection check failure", "warn", "event");
return false;
}
},
// aliases to support DOM event subscription clean up when the last
// subscriber is detached. deleteAndClean overrides the DOM event's wrapper
// CustomEvent _delete method.
_ceProtoDelete = Y.CustomEvent.prototype._delete,
_deleteAndClean = function(s) {
var ret = _ceProtoDelete.apply(this, arguments);
if (!this.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;
// Y.log('onAvailable registered for: ' + id);
for (i=0; i<a.length; i=i+1) {
_avail.push({
id: a[i],
fn: fn,
obj: p_obj,
override: p_override,
checkReady: checkContent,
compat: compat
});
}
_retryCount = this.POLL_RETRYS;
// We want the first test to be immediate, but async
setTimeout(Event._poll, 0);
availHandle = new Y.EventHandle({
_delete: function() {
// set by the event system for lazy DOM listeners
if (availHandle.handle) {
availHandle.handle.detach();
return;
}
var i, j;
// otherwise try to remove the onAvailable listener(s)
for (i = 0; i < a.length; i++) {
for (j = 0; j < _avail.length; j++) {
if (a[i] === _avail[j].id) {
_avail.splice(j, 1);
}
}
}
}
});
return availHandle;
},
/**
* Works the same way as onAvailable, but additionally checks the
* state of sibling elements to determine if the content of the
* available element is safe to modify.
*
* <p>The callback is executed with a single parameter:
* the custom object parameter, if provided.</p>
*
* @method onContentReady
*
* @param {string} id the id of the element to look for.
* @param {function} fn what to execute when the element is ready.
* @param {object} obj an optional object to be passed back as
* a parameter to fn.
* @param {boolean|object} override If set to true, fn will execute
* in the context of p_obj. If an object, fn will
* exectute in the context of that object
*
* @static
* @deprecated Use Y.on("contentready")
*/
// @TODO fix arguments
onContentReady: function(id, fn, obj, override, compat) {
return Event.onAvailable(id, fn, obj, override, true, compat);
},
/**
* Adds an event listener
*
* @method attach
*
* @param {String} type The type of event to append
* @param {Function} fn The method the event invokes
* @param {String|HTMLElement|Array|NodeList} el An id, an element
* reference, or a collection of ids and/or elements to assign the
* listener to.
* @param {Object} context optional context object
* @param {Boolean|object} args 0..n arguments to pass to the callback
* @return {EventHandle} an object to that can be used to detach the listener
*
* @static
*/
attach: function(type, fn, el, context) {
return Event._attach(Y.Array(arguments, 0, true));
},
_createWrapper: function (el, type, capture, compat, facade) {
var cewrapper,
ek = Y.stamp(el),
key = 'event:' + ek + type;
if (false === facade) {
key += 'native';
}
if (capture) {
key += 'capture';
}
cewrapper = _wrappers[key];
if (!cewrapper) {
// create CE wrapper
cewrapper = Y.publish(key, {
silent: true,
bubbles: false,
contextFn: function() {
if (compat) {
return cewrapper.el;
} else {
cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el);
return cewrapper.nodeRef;
}
}
});
cewrapper.overrides = {};
// for later removeListener calls
cewrapper.el = el;
cewrapper.key = key;
cewrapper.domkey = ek;
cewrapper.type = type;
cewrapper.fn = function(e) {
cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade))));
};
cewrapper.capture = capture;
if (el == win && type == "load") {
// window load happens once
cewrapper.fireOnce = true;
_windowLoadKey = key;
}
cewrapper._delete = _deleteAndClean;
_wrappers[key] = cewrapper;
_el_events[ek] = _el_events[ek] || {};
_el_events[ek][key] = cewrapper;
add(el, type, cewrapper.fn, capture);
}
return cewrapper;
},
_attach: function(args, conf) {
var compat,
handles, oEl, cewrapper, context,
fireNow = false, ret,
type = args[0],
fn = args[1],
el = args[2] || win,
facade = conf && conf.facade,
capture = conf && conf.capture,
overrides = conf && conf.overrides;
if (args[args.length-1] === COMPAT_ARG) {
compat = true;
}
if (!fn || !fn.call) {
// throw new TypeError(type + " attach call failed, callback undefined");
Y.log(type + " attach call failed, invalid callback", "error", "event");
return false;
}
// The el argument can be an array of elements or element ids.
if (shouldIterate(el)) {
handles=[];
Y.each(el, function(v, k) {
args[2] = v;
handles.push(Event._attach(args.slice(), conf));
});
// return (handles.length === 1) ? handles[0] : handles;
return new Y.EventHandle(handles);
// If the el argument is a string, we assume it is
// actually the id of the element. If the page is loaded
// we convert el to the actual element, otherwise we
// defer attaching the event until the element is
// ready
} else if (Y.Lang.isString(el)) {
// oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el);
if (compat) {
oEl = Y.DOM.byId(el);
} else {
oEl = Y.Selector.query(el);
switch (oEl.length) {
case 0:
oEl = null;
break;
case 1:
oEl = oEl[0];
break;
default:
args[2] = oEl;
return Event._attach(args, conf);
}
}
if (oEl) {
el = oEl;
// Not found = defer adding the event until the element is available
} else {
// Y.log(el + ' not found');
ret = Event.onAvailable(el, function() {
// Y.log('lazy attach: ' + args);
ret.handle = Event._attach(args, conf);
}, Event, true, false, compat);
return ret;
}
}
// Element should be an html element or node
if (!el) {
Y.log("unable to attach event " + type, "warn", "event");
return false;
}
if (Y.Node && Y.instanceOf(el, Y.Node)) {
el = Y.Node.getDOMNode(el);
}
cewrapper = Event._createWrapper(el, type, capture, compat, facade);
if (overrides) {
Y.mix(cewrapper.overrides, overrides);
}
if (el == win && type == "load") {
// if the load is complete, fire immediately.
// all subscribers, including the current one
// will be notified.
if (YUI.Env.windowLoaded) {
fireNow = true;
}
}
if (compat) {
args.pop();
}
context = args[3];
// set context to the Node if not specified
// ret = cewrapper.on.apply(cewrapper, trimmedArgs);
ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null);
if (fireNow) {
cewrapper.fire();
}
return ret;
},
/**
* Removes an event listener. Supports the signature the event was bound
* with, but the preferred way to remove listeners is using the handle
* that is returned when using Y.on
*
* @method detach
*
* @param {String} type the type of event to remove.
* @param {Function} fn the method the event invokes. If fn is
* undefined, then all event handlers for the type of event are
* removed.
* @param {String|HTMLElement|Array|NodeList|EventHandle} el An
* event handle, an id, an element reference, or a collection
* of ids and/or elements to remove the listener from.
* @return {boolean} true if the unbind was successful, false otherwise.
* @static
*/
detach: function(type, fn, el, obj) {
var args=Y.Array(arguments, 0, true), compat, l, ok, i,
id, ce;
if (args[args.length-1] === COMPAT_ARG) {
compat = true;
// args.pop();
}
if (type && type.detach) {
return type.detach();
}
// The el argument can be a string
if (typeof el == "string") {
// el = (compat) ? Y.DOM.byId(el) : Y.all(el);
if (compat) {
el = Y.DOM.byId(el);
} else {
el = Y.Selector.query(el);
l = el.length;
if (l < 1) {
el = null;
} else if (l == 1) {
el = el[0];
}
}
// return Event.detach.apply(Event, args);
}
if (!el) {
return false;
}
if (el.detach) {
args.splice(2, 1);
return el.detach.apply(el, args);
// The el argument can be an array of elements or element ids.
} else if (shouldIterate(el)) {
ok = true;
for (i=0, l=el.length; i<l; ++i) {
args[2] = el[i];
ok = ( Y.Event.detach.apply(Y.Event, args) && ok );
}
return ok;
}
if (!type || !fn || !fn.call) {
return Event.purgeElement(el, false, type);
}
id = 'event:' + Y.stamp(el) + type;
ce = _wrappers[id];
if (ce) {
return ce.detach(fn);
} else {
return false;
}
},
/**
* Finds the event in the window object, the caller's arguments, or
* in the arguments of another method in the callstack. This is
* executed automatically for events registered through the event
* manager, so the implementer should not normally need to execute
* this function at all.
* @method getEvent
* @param {Event} e the event parameter from the handler
* @param {HTMLElement} el the element the listener was attached to
* @return {Event} the event
* @static
*/
getEvent: function(e, el, noFacade) {
var ev = e || win.event;
return (noFacade) ? ev :
new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]);
},
/**
* Generates an unique ID for the element if it does not already
* have one.
* @method generateId
* @param el the element to create the id for
* @return {string} the resulting id of the element
* @static
*/
generateId: function(el) {
return Y.DOM.generateID(el);
},
/**
* We want to be able to use getElementsByTagName as a collection
* to attach a group of events to. Unfortunately, different
* browsers return different types of collections. This function
* tests to determine if the object is array-like. It will also
* fail if the object is an array, but is empty.
* @method _isValidCollection
* @param o the object to test
* @return {boolean} true if the object is array-like and populated
* @deprecated was not meant to be used directly
* @static
* @private
*/
_isValidCollection: shouldIterate,
/**
* hook up any deferred listeners
* @method _load
* @static
* @private
*/
_load: function(e) {
if (!_loadComplete) {
// Y.log('Load Complete', 'info', 'event');
_loadComplete = true;
// Just in case DOMReady did not go off for some reason
// E._ready();
if (Y.fire) {
Y.fire(EVENT_READY);
}
// Available elements may not have been detected before the
// window load event fires. Try to find them now so that the
// the user is more likely to get the onAvailable notifications
// before the window load notification
Event._poll();
}
},
/**
* Polling function that runs before the onload event fires,
* attempting to attach to DOM Nodes as soon as they are
* available
* @method _poll
* @static
* @private
*/
_poll: function() {
if (Event.locked) {
return;
}
if (Y.UA.ie && !YUI.Env.DOMReady) {
// Hold off if DOMReady has not fired and check current
// readyState to protect against the IE operation aborted
// issue.
Event.startInterval();
return;
}
Event.locked = true;
// Y.log.debug("poll");
// keep trying until after the page is loaded. We need to
// check the page load state prior to trying to bind the
// elements so that we can be certain all elements have been
// tested appropriately
var i, len, item, el, notAvail, executeItem,
tryAgain = !_loadComplete;
if (!tryAgain) {
tryAgain = (_retryCount > 0);
}
// onAvailable
notAvail = [];
executeItem = function (el, item) {
var context, ov = item.override;
try {
if (item.compat) {
if (item.override) {
if (ov === true) {
context = item.obj;
} else {
context = ov;
}
} else {
context = el;
}
item.fn.call(context, item.obj);
} else {
context = item.obj || Y.one(el);
item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []);
}
} catch (e) {
Y.log("Error in available or contentReady callback", 'error', 'event');
}
};
// onAvailable
for (i=0,len=_avail.length; i<len; ++i) {
item = _avail[i];
if (item && !item.checkReady) {
// el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
if (el) {
// Y.log('avail: ' + el);
executeItem(el, item);
_avail[i] = null;
} else {
// Y.log('NOT avail: ' + el);
notAvail.push(item);
}
}
}
// onContentReady
for (i=0,len=_avail.length; i<len; ++i) {
item = _avail[i];
if (item && item.checkReady) {
// el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
if (el) {
// The element is available, but not necessarily ready
// @todo should we test parentNode.nextSibling?
if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) {
executeItem(el, item);
_avail[i] = null;
}
} else {
notAvail.push(item);
}
}
}
_retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1;
if (tryAgain) {
// we may need to strip the nulled out items here
Event.startInterval();
} else {
clearInterval(Event._interval);
Event._interval = null;
}
Event.locked = false;
return;
},
/**
* Removes all listeners attached to the given element via addListener.
* Optionally, the node's children can also be purged.
* Optionally, you can specify a specific type of event to remove.
* @method purgeElement
* @param {HTMLElement} el the element to purge
* @param {boolean} recurse recursively purge this element's children
* as well. Use with caution.
* @param {string} type optional type of listener to purge. If
* left out, all listeners will be removed
* @static
*/
purgeElement: function(el, recurse, type) {
// var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el,
var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el,
lis = Event.getListeners(oEl, type), i, len, children, child;
if (recurse && oEl) {
lis = lis || [];
children = Y.Selector.query('*', oEl);
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 {CustomEvent} the custom event wrapper for the DOM event(s)
* @static
*/
getListeners: function(el, type) {
var ek = Y.stamp(el, true), evts = _el_events[ek],
results=[] , key = (type) ? 'event:' + ek + type : null,
adapters = _eventenv.plugins;
if (!evts) {
return null;
}
if (key) {
// look for synthetic events
if (adapters[type] && adapters[type].eventDef) {
key += '_synth';
}
if (evts[key]) {
results.push(evts[key]);
}
// get native events as well
key += 'native';
if (evts[key]) {
results.push(evts[key]);
}
} else {
Y.each(evts, function(v, k) {
results.push(v);
});
}
return (results.length) ? results : null;
},
/**
* Removes all listeners registered by pe.event. Called
* automatically during the unload event.
* @method _unload
* @static
* @private
*/
_unload: function(e) {
Y.each(_wrappers, function(v, k) {
if (v.type == 'unload') {
v.fire(e);
}
v.detachAll();
});
remove(win, "unload", onUnload);
},
/**
* Adds a DOM event directly without the caching, cleanup, context adj, etc
*
* @method nativeAdd
* @param {HTMLElement} el the element to bind the handler to
* @param {string} type the type of event handler
* @param {function} fn the callback to invoke
* @param {boolen} capture capture or bubble phase
* @static
* @private
*/
nativeAdd: add,
/**
* Basic remove listener
*
* @method nativeRemove
* @param {HTMLElement} el the element to bind the handler to
* @param {string} type the type of event handler
* @param {function} fn the callback to invoke
* @param {boolen} capture capture or bubble phase
* @static
* @private
*/
nativeRemove: remove
};
}();
Y.Event = Event;
if (config.injected || YUI.Env.windowLoaded) {
onLoad();
} else {
add(win, "load", onLoad);
}
// Process onAvailable/onContentReady items when when the DOM is ready in IE
if (Y.UA.ie) {
Y.on(EVENT_READY, Event._poll);
}
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('pluginhost-base', function(Y) {
/**
* Provides the augmentable PluginHost interface, which can be added to any class.
* @module pluginhost
*/
/**
* Provides the augmentable PluginHost interface, which can be added to any class.
* @module pluginhost-base
*/
/**
* <p>
* An augmentable class, which provides the augmented class with the ability to host plugins.
* It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can
* be used to add or remove plugins from instances of the class.
* </p>
*
* <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using
* the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method.
*
* For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host):
* <xmp>
* var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]});
* </xmp>
* </p>
* <p>
* Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a>
* methods should be invoked by the host class at the appropriate point in the host's lifecyle.
* </p>
*
* @class Plugin.Host
*/
var L = Y.Lang;
function PluginHost() {
this._plugins = {};
}
PluginHost.prototype = {
/**
* Adds a plugin to the host object. This will instantiate the
* plugin and attach it to the configured namespace on the host object.
*
* @method plug
* @chainable
* @param P {Function | Object |Array} Accepts the plugin class, or an
* object with a "fn" property specifying the plugin class and
* a "cfg" property specifying the configuration for the Plugin.
* <p>
* Additionally an Array can also be passed in, with the above function or
* object values, allowing the user to add multiple plugins in a single call.
* </p>
* @param config (Optional) If the first argument is the plugin class, the second argument
* can be the configuration for the plugin.
* @return {Base} A reference to the host object
*/
plug: function(Plugin, config) {
var i, ln, ns;
if (L.isArray(Plugin)) {
for (i = 0, ln = Plugin.length; i < ln; i++) {
this.plug(Plugin[i]);
}
} else {
if (Plugin && !L.isFunction(Plugin)) {
config = Plugin.cfg;
Plugin = Plugin.fn;
}
// Plugin should be fn by now
if (Plugin && Plugin.NS) {
ns = Plugin.NS;
config = config || {};
config.host = this;
if (this.hasPlugin(ns)) {
// Update config
this[ns].setAttrs(config);
} else {
// Create new instance
this[ns] = new Plugin(config);
this._plugins[ns] = Plugin;
}
}
else { Y.log("Attempt to plug in an invalid plugin. Host:" + this + ", Plugin:" + Plugin); }
}
return this;
},
/**
* Removes a plugin from the host object. This will destroy the
* plugin instance and delete the namepsace from the host object.
*
* @method unplug
* @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided,
* all registered plugins are unplugged.
* @return {Base} A reference to the host object
* @chainable
*/
unplug: function(plugin) {
var ns = plugin,
plugins = this._plugins;
if (plugin) {
if (L.isFunction(plugin)) {
ns = plugin.NS;
if (ns && (!plugins[ns] || plugins[ns] !== plugin)) {
ns = null;
}
}
if (ns) {
if (this[ns]) {
this[ns].destroy();
delete this[ns];
}
if (plugins[ns]) {
delete plugins[ns];
}
}
} else {
for (ns in this._plugins) {
if (this._plugins.hasOwnProperty(ns)) {
this.unplug(ns);
}
}
}
return this;
},
/**
* Determines if a plugin has plugged into this host.
*
* @method hasPlugin
* @param {String} ns The plugin's namespace
* @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not.
*/
hasPlugin : function(ns) {
return (this._plugins[ns] && this[ns]);
},
/**
* Initializes static plugins registered on the host (using the
* Base.plug static method) and any plugins passed to the
* instance through the "plugins" configuration property.
*
* @method _initPlugins
* @param {Config} config The configuration object with property name/value pairs.
* @private
*/
_initPlugins: function(config) {
this._plugins = this._plugins || {};
if (this._initConfigPlugins) {
this._initConfigPlugins(config);
}
},
/**
* Unplugs and destroys all plugins on the host
* @method _destroyPlugins
* @private
*/
_destroyPlugins: function() {
this.unplug();
}
};
Y.namespace("Plugin").Host = PluginHost;
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('pluginhost-config', function(Y) {
/**
* Adds pluginhost constructor configuration and static configuration support
* @submodule pluginhost-config
*/
var PluginHost = Y.Plugin.Host,
L = Y.Lang;
/**
* A protected initialization method, used by the host class to initialize
* plugin configurations passed the constructor, through the config object.
*
* Host objects should invoke this method at the appropriate time in their
* construction lifecycle.
*
* @method _initConfigPlugins
* @param {Object} config The configuration object passed to the constructor
* @protected
* @for Plugin.Host
*/
PluginHost.prototype._initConfigPlugins = function(config) {
// Class Configuration
var classes = (this._getClasses) ? this._getClasses() : [this.constructor],
plug = [],
unplug = {},
constructor, i, classPlug, classUnplug, pluginClassName;
// TODO: Room for optimization. Can we apply statically/unplug in same pass?
for (i = classes.length - 1; i >= 0; i--) {
constructor = classes[i];
classUnplug = constructor._UNPLUG;
if (classUnplug) {
// subclasses over-write
Y.mix(unplug, classUnplug, true);
}
classPlug = constructor._PLUG;
if (classPlug) {
// subclasses over-write
Y.mix(plug, classPlug, true);
}
}
for (pluginClassName in plug) {
if (plug.hasOwnProperty(pluginClassName)) {
if (!unplug[pluginClassName]) {
this.plug(plug[pluginClassName]);
}
}
}
// User Configuration
if (config && config.plugins) {
this.plug(config.plugins);
}
};
/**
* Registers plugins to be instantiated at the class level (plugins
* which should be plugged into every instance of the class by default).
*
* @method plug
* @static
*
* @param {Function} hostClass The host class on which to register the plugins
* @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined)
* @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin
* @for Plugin.Host
*/
PluginHost.plug = function(hostClass, plugin, config) {
// Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ]
var p, i, l, name;
if (hostClass !== Y.Base) {
hostClass._PLUG = hostClass._PLUG || {};
if (!L.isArray(plugin)) {
if (config) {
plugin = {fn:plugin, cfg:config};
}
plugin = [plugin];
}
for (i = 0, l = plugin.length; i < l;i++) {
p = plugin[i];
name = p.NAME || p.fn.NAME;
hostClass._PLUG[name] = p;
}
}
};
/**
* Unregisters any class level plugins which have been registered by the host class, or any
* other class in the hierarchy.
*
* @method unplug
* @static
*
* @param {Function} hostClass The host class from which to unregister the plugins
* @param {Function | Array} plugin The plugin class, or an array of plugin classes
* @for Plugin.Host
*/
PluginHost.unplug = function(hostClass, plugin) {
var p, i, l, name;
if (hostClass !== Y.Base) {
hostClass._UNPLUG = hostClass._UNPLUG || {};
if (!L.isArray(plugin)) {
plugin = [plugin];
}
for (i = 0, l = plugin.length; i < l; i++) {
p = plugin[i];
name = p.NAME;
if (!hostClass._PLUG[name]) {
hostClass._UNPLUG[name] = p;
} else {
delete hostClass._PLUG[name];
}
}
}
};
}, '@VERSION@' ,{requires:['pluginhost-base']});
YUI.add('event-delegate', function(Y) {
/**
* Adds event delegation support to the library.
*
* @module event
* @submodule event-delegate
*/
var toArray = Y.Array,
YLang = Y.Lang,
isString = YLang.isString,
isObject = YLang.isObject,
isArray = YLang.isArray,
selectorTest = Y.Selector.test,
detachCategories = Y.Env.evt.handles;
/**
* <p>Sets up event delegation on a container element. The delegated event
* will use a supplied selector or filtering function to test if the event
* references at least one node that should trigger the subscription
* callback.</p>
*
* <p>Selector string filters will trigger the callback if the event originated
* from a node that matches it or is contained in a node that matches it.
* Function filters are called for each Node up the parent axis to the
* subscribing container node, and receive at each level the Node and the event
* object. The function should return true (or a truthy value) if that Node
* should trigger the subscription callback. Note, it is possible for filters
* to match multiple Nodes for a single event. In this case, the delegate
* callback will be executed for each matching Node.</p>
*
* <p>For each matching Node, the callback will be executed with its 'this'
* object set to the Node matched by the filter (unless a specific context was
* provided during subscription), and the provided event's
* <code>currentTarget</code> will also be set to the matching Node. The
* containing Node from which the subscription was originally made can be
* referenced as <code>e.container</code>.
*
* @method delegate
* @param type {String} the event type to delegate
* @param fn {Function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param el {String|node} the element that is the delegation container
* @param filter {string|Function} a selector that must match the target of the
* event or a function to test target and its parents for a match
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @static
* @for Event
*/
function delegate(type, fn, el, filter) {
var args = toArray(arguments, 0, true),
query = isString(el) ? el : null,
typeBits, synth, container, categories, cat, i, len, handles, handle;
// Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...);
// and Y.delegate(['click', 'key'], fn, el, filter, ...);
if (isObject(type)) {
handles = [];
if (isArray(type)) {
for (i = 0, len = type.length; i < len; ++i) {
args[0] = type[i];
handles.push(Y.delegate.apply(Y, args));
}
} else {
// Y.delegate({'click', fn}, el, filter) =>
// Y.delegate('click', fn, el, filter)
args.unshift(null); // one arg becomes two; need to make space
for (i in type) {
if (type.hasOwnProperty(i)) {
args[0] = i;
args[1] = type[i];
handles.push(Y.delegate.apply(Y, args));
}
}
}
return new Y.EventHandle(handles);
}
typeBits = type.split(/\|/);
if (typeBits.length > 1) {
cat = typeBits.shift();
args[0] = type = typeBits.shift();
}
synth = Y.Node.DOM_EVENTS[type];
if (isObject(synth) && synth.delegate) {
handle = synth.delegate.apply(synth, arguments);
}
if (!handle) {
if (!type || !fn || !el || !filter) {
Y.log("delegate requires type, callback, parent, & filter", "warn");
return;
}
container = (query) ? Y.Selector.query(query, null, true) : el;
if (!container && isString(el)) {
handle = Y.on('available', function () {
Y.mix(handle, Y.delegate.apply(Y, args), true);
}, el);
}
if (!handle && container) {
args.splice(2, 2, container); // remove the filter
handle = Y.Event._attach(args, { facade: false });
handle.sub.filter = filter;
handle.sub._notify = delegate.notifySub;
}
}
if (handle && cat) {
categories = detachCategories[cat] || (detachCategories[cat] = {});
categories = categories[type] || (categories[type] = []);
categories.push(handle);
}
return handle;
}
/**
Overrides the <code>_notify</code> method on the normal DOM subscription to
inject the filtering logic and only proceed in the case of a match.
This method is hosted as a private property of the `delegate` method
(e.g. `Y.delegate.notifySub`)
@method notifySub
@param thisObj {Object} default 'this' object for the callback
@param args {Array} arguments passed to the event's <code>fire()</code>
@param ce {CustomEvent} the custom event managing the DOM subscriptions for
the subscribed event on the subscribing node.
@return {Boolean} false if the event was stopped
@private
@static
@since 3.2.0
**/
delegate.notifySub = function (thisObj, args, ce) {
// Preserve args for other subscribers
args = args.slice();
if (this.args) {
args.push.apply(args, this.args);
}
// Only notify subs if the event occurred on a targeted element
var currentTarget = delegate._applyFilter(this.filter, args, ce),
//container = e.currentTarget,
e, i, len, ret;
if (currentTarget) {
// Support multiple matches up the the container subtree
currentTarget = toArray(currentTarget);
// The second arg is the currentTarget, but we'll be reusing this
// facade, replacing the currentTarget for each use, so it doesn't
// matter what element we seed it with.
e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce);
e.container = Y.one(ce.el);
for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) {
e.currentTarget = Y.one(currentTarget[i]);
ret = this.fn.apply(this.context || e.currentTarget, args);
if (ret === false) { // stop further notifications
break;
}
}
return ret;
}
};
/**
Compiles a selector string into a filter function to identify whether
Nodes along the parent axis of an event's target should trigger event
notification.
This function is memoized, so previously compiled filter functions are
returned if the same selector string is provided.
This function may be useful when defining synthetic events for delegate
handling.
Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`).
@method compileFilter
@param selector {String} the selector string to base the filtration on
@return {Function}
@since 3.2.0
@static
**/
delegate.compileFilter = Y.cached(function (selector) {
return function (target, e) {
return selectorTest(target._node, selector,
(e.currentTarget === e.target) ? null : e.currentTarget._node);
};
});
/**
Walks up the parent axis of an event's target, and tests each element
against a supplied filter function. If any Nodes, including the container,
satisfy the filter, the delegated callback will be triggered for each.
Hosted as a protected property of the `delegate` method (e.g.
`Y.delegate._applyFilter`).
@method _applyFilter
@param filter {Function} boolean function to test for inclusion in event
notification
@param args {Array} the arguments that would be passed to subscribers
@param ce {CustomEvent} the DOM event wrapper
@return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter
@protected
**/
delegate._applyFilter = function (filter, args, ce) {
var e = args[0],
container = ce.el, // facadeless events in IE, have no e.currentTarget
target = e.target || e.srcElement,
match = [],
isContainer = false;
// Resolve text nodes to their containing element
if (target.nodeType === 3) {
target = target.parentNode;
}
// passing target as the first arg rather than leaving well enough alone
// making 'this' in the filter function refer to the target. This is to
// support bound filter functions.
args.unshift(target);
if (isString(filter)) {
while (target) {
isContainer = (target === container);
if (selectorTest(target, filter, (isContainer ? null: container))) {
match.push(target);
}
if (isContainer) {
break;
}
target = target.parentNode;
}
} else {
// filter functions are implementer code and should receive wrappers
args[0] = Y.one(target);
args[1] = new Y.DOMEventFacade(e, container, ce);
while (target) {
// filter(target, e, extra args...) - this === target
if (filter.apply(args[0], args)) {
match.push(target);
}
if (target === container) {
break;
}
target = target.parentNode;
args[0] = Y.one(target);
}
args[1] = e; // restore the raw DOM event
}
if (match.length <= 1) {
match = match[0]; // single match or undefined
}
// remove the target
args.shift();
return match;
};
/**
* Sets up event delegation on a container element. The delegated event
* will use a supplied filter to test if the callback should be executed.
* This filter can be either a selector string or a function that returns
* a Node to use as the currentTarget for the event.
*
* The event object for the delegated event is supplied to the callback
* function. It is modified slightly in order to support all properties
* that may be needed for event delegation. 'currentTarget' is set to
* the element that matched the selector string filter or the Node returned
* from the filter function. 'container' is set to the element that the
* listener is delegated from (this normally would be the 'currentTarget').
*
* Filter functions will be called with the arguments that would be passed to
* the callback function, including the event object as the first parameter.
* The function should return false (or a falsey value) if the success criteria
* aren't met, and the Node to use as the event's currentTarget and 'this'
* object if they are.
*
* @method delegate
* @param type {string} the event type to delegate
* @param fn {function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param el {string|node} the element that is the delegation container
* @param filter {string|function} a selector that must match the target of the
* event or a function that returns a Node or false.
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.delegate = Y.Event.delegate = delegate;
}, '@VERSION@' ,{requires:['node-base']});
YUI.add('node-event-delegate', function(Y) {
/**
* Functionality to make the node a delegated event container
* @module node
* @submodule node-event-delegate
*/
/**
* <p>Sets up a delegation listener for an event occurring inside the Node.
* The delegated event will be verified against a supplied selector or
* filtering function to test if the event references at least one node that
* should trigger the subscription callback.</p>
*
* <p>Selector string filters will trigger the callback if the event originated
* from a node that matches it or is contained in a node that matches it.
* Function filters are called for each Node up the parent axis to the
* subscribing container node, and receive at each level the Node and the event
* object. The function should return true (or a truthy value) if that Node
* should trigger the subscription callback. Note, it is possible for filters
* to match multiple Nodes for a single event. In this case, the delegate
* callback will be executed for each matching Node.</p>
*
* <p>For each matching Node, the callback will be executed with its 'this'
* object set to the Node matched by the filter (unless a specific context was
* provided during subscription), and the provided event's
* <code>currentTarget</code> will also be set to the matching Node. The
* containing Node from which the subscription was originally made can be
* referenced as <code>e.container</code>.
*
* @method delegate
* @param type {String} the event type to delegate
* @param fn {Function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param spec {String|Function} a selector that must match the target of the
* event or a function to test target and its parents for a match
* @param context {Object} optional argument that specifies what 'this' refers to.
* @param args* {any} 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for Node
*/
Y.Node.prototype.delegate = function(type) {
var args = Y.Array(arguments, 0, true),
index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2;
args.splice(index, 0, this._node);
return Y.delegate.apply(Y, args);
};
}, '@VERSION@' ,{requires:['node-base', 'event-delegate']});
YUI.add('node-pluginhost', function(Y) {
/**
* @module node
* @submodule node-pluginhost
*/
/**
* Registers plugins to be instantiated at the class level (plugins
* which should be plugged into every instance of Node by default).
*
* @method plug
* @static
* @for Node
* @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined)
* @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin
*/
Y.Node.plug = function() {
var args = Y.Array(arguments);
args.unshift(Y.Node);
Y.Plugin.Host.plug.apply(Y.Base, args);
return Y.Node;
};
/**
* Unregisters any class level plugins which have been registered by the Node
*
* @method unplug
* @static
*
* @param {Function | Array} plugin The plugin class, or an array of plugin classes
*/
Y.Node.unplug = function() {
var args = Y.Array(arguments);
args.unshift(Y.Node);
Y.Plugin.Host.unplug.apply(Y.Base, args);
return Y.Node;
};
Y.mix(Y.Node, Y.Plugin.Host, false, null, 1);
// allow batching of plug/unplug via NodeList
// doesn't use NodeList.importMethod because we need real Nodes (not tmpNode)
Y.NodeList.prototype.plug = function() {
var args = arguments;
Y.NodeList.each(this, function(node) {
Y.Node.prototype.plug.apply(Y.one(node), args);
});
};
Y.NodeList.prototype.unplug = function() {
var args = arguments;
Y.NodeList.each(this, function(node) {
Y.Node.prototype.unplug.apply(Y.one(node), args);
});
};
}, '@VERSION@' ,{requires:['node-base', 'pluginhost']});
YUI.add('node-screen', function(Y) {
/**
* Extended Node interface for managing regions and screen positioning.
* Adds support for positioning elements and normalizes window size and scroll detection.
* @module node
* @submodule node-screen
*/
// these are all "safe" returns, no wrapping required
Y.each([
/**
* Returns the inner width of the viewport (exludes scrollbar).
* @config winWidth
* @for Node
* @type {Int}
*/
'winWidth',
/**
* Returns the inner height of the viewport (exludes scrollbar).
* @config winHeight
* @type {Int}
*/
'winHeight',
/**
* Document width
* @config winHeight
* @type {Int}
*/
'docWidth',
/**
* Document height
* @config docHeight
* @type {Int}
*/
'docHeight',
/**
* Pixel distance the page has been scrolled horizontally
* @config docScrollX
* @type {Int}
*/
'docScrollX',
/**
* Pixel distance the page has been scrolled vertically
* @config docScrollY
* @type {Int}
*/
'docScrollY'
],
function(name) {
Y.Node.ATTRS[name] = {
getter: function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(Y.Node.getDOMNode(this));
return Y.DOM[name].apply(this, args);
}
};
}
);
Y.Node.ATTRS.scrollLeft = {
getter: function() {
var node = Y.Node.getDOMNode(this);
return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node);
},
setter: function(val) {
var node = Y.Node.getDOMNode(this);
if (node) {
if ('scrollLeft' in node) {
node.scrollLeft = val;
} else if (node.document || node.nodeType === 9) {
Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc
}
} else {
Y.log('unable to set scrollLeft for ' + node, 'error', 'Node');
}
}
};
Y.Node.ATTRS.scrollTop = {
getter: function() {
var node = Y.Node.getDOMNode(this);
return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node);
},
setter: function(val) {
var node = Y.Node.getDOMNode(this);
if (node) {
if ('scrollTop' in node) {
node.scrollTop = val;
} else if (node.document || node.nodeType === 9) {
Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc
}
} else {
Y.log('unable to set scrollTop for ' + node, 'error', 'Node');
}
}
};
Y.Node.importMethod(Y.DOM, [
/**
* Gets the current position of the node in page coordinates.
* @method getXY
* @for Node
* @return {Array} The XY position of the node
*/
'getXY',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setXY
* @param {Array} xy Contains X & Y values for new position (coordinates are page-based)
* @chainable
*/
'setXY',
/**
* Gets the current position of the node in page coordinates.
* @method getX
* @return {Int} The X position of the node
*/
'getX',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setX
* @param {Int} x X value for new position (coordinates are page-based)
* @chainable
*/
'setX',
/**
* Gets the current position of the node in page coordinates.
* @method getY
* @return {Int} The Y position of the node
*/
'getY',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setY
* @param {Int} y Y value for new position (coordinates are page-based)
* @chainable
*/
'setY',
/**
* Swaps the XY position of this node with another node.
* @method swapXY
* @param {Node | HTMLElement} otherNode The node to swap with.
* @chainable
*/
'swapXY'
]);
/**
* @module node
* @submodule node-screen
*/
/**
* Returns a region object for the node
* @config region
* @for Node
* @type Node
*/
Y.Node.ATTRS.region = {
getter: function() {
var node = this.getDOMNode(),
region;
if (node && !node.tagName) {
if (node.nodeType === 9) { // document
node = node.documentElement;
}
}
if (Y.DOM.isWindow(node)) {
region = Y.DOM.viewportRegion(node);
} else {
region = Y.DOM.region(node);
}
return region;
}
};
/**
* Returns a region object for the node's viewport
* @config viewportRegion
* @type Node
*/
Y.Node.ATTRS.viewportRegion = {
getter: function() {
return Y.DOM.viewportRegion(Y.Node.getDOMNode(this));
}
};
Y.Node.importMethod(Y.DOM, 'inViewportRegion');
// these need special treatment to extract 2nd node arg
/**
* Compares the intersection of the node with another node or region
* @method intersect
* @for Node
* @param {Node|Object} node2 The node or region to compare with.
* @param {Object} altRegion An alternate region to use (rather than this node's).
* @return {Object} An object representing the intersection of the regions.
*/
Y.Node.prototype.intersect = function(node2, altRegion) {
var node1 = Y.Node.getDOMNode(this);
if (Y.instanceOf(node2, Y.Node)) { // might be a region object
node2 = Y.Node.getDOMNode(node2);
}
return Y.DOM.intersect(node1, node2, altRegion);
};
/**
* Determines whether or not the node is within the giving region.
* @method inRegion
* @param {Node|Object} node2 The node or region to compare with.
* @param {Boolean} all Whether or not all of the node must be in the region.
* @param {Object} altRegion An alternate region to use (rather than this node's).
* @return {Object} An object representing the intersection of the regions.
*/
Y.Node.prototype.inRegion = function(node2, all, altRegion) {
var node1 = Y.Node.getDOMNode(this);
if (Y.instanceOf(node2, Y.Node)) { // might be a region object
node2 = Y.Node.getDOMNode(node2);
}
return Y.DOM.inRegion(node1, node2, all, altRegion);
};
}, '@VERSION@' ,{requires:['node-base', 'dom-screen']});
YUI.add('node-style', function(Y) {
(function(Y) {
/**
* Extended Node interface for managing node styles.
* @module node
* @submodule node-style
*/
Y.mix(Y.Node.prototype, {
/**
* Sets a style property of the node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyle
* @param {String} attr The style attribute to set.
* @param {String|Number} val The value.
* @chainable
*/
setStyle: function(attr, val) {
Y.DOM.setStyle(this._node, attr, val);
return this;
},
/**
* Sets multiple style properties on the node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyles
* @param {Object} hash An object literal of property:value pairs.
* @chainable
*/
setStyles: function(hash) {
Y.DOM.setStyles(this._node, hash);
return this;
},
/**
* Returns the style's current value.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getStyle
* @for Node
* @param {String} attr The style attribute to retrieve.
* @return {String} The current value of the style property for the element.
*/
getStyle: function(attr) {
return Y.DOM.getStyle(this._node, attr);
},
/**
* Returns the computed value for the given style property.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getComputedStyle
* @param {String} attr The style attribute to retrieve.
* @return {String} The computed value of the style property for the element.
*/
getComputedStyle: function(attr) {
return Y.DOM.getComputedStyle(this._node, attr);
}
});
/**
* Returns an array of values for each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getStyle
* @for NodeList
* @see Node.getStyle
* @param {String} attr The style attribute to retrieve.
* @return {Array} The current values of the style property for the element.
*/
/**
* Returns an array of the computed value for each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getComputedStyle
* @see Node.getComputedStyle
* @param {String} attr The style attribute to retrieve.
* @return {Array} The computed values for each node.
*/
/**
* Sets a style property on each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyle
* @see Node.setStyle
* @param {String} attr The style attribute to set.
* @param {String|Number} val The value.
* @chainable
*/
/**
* Sets multiple style properties on each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyles
* @see Node.setStyles
* @param {Object} hash An object literal of property:value pairs.
* @chainable
*/
// These are broken out to handle undefined return (avoid false positive for
// chainable)
Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']);
})(Y);
}, '@VERSION@' ,{requires:['dom-style', 'node-base']});
YUI.add('querystring-stringify-simple', function(Y) {
/*global Y */
/**
* <p>Provides Y.QueryString.stringify method for converting objects to Query Strings.
* This is a subset implementation of the full querystring-stringify.</p>
* <p>This module provides the bare minimum functionality (encoding a hash of simple values),
* without the additional support for nested data structures. Every key-value pair is
* encoded by encodeURIComponent.</p>
* <p>This module provides a minimalistic way for io to handle single-level objects
* as transaction data.</p>
*
* @module querystring
* @submodule querystring-stringify-simple
* @for QueryString
* @static
*/
var QueryString = Y.namespace("QueryString"),
EUC = encodeURIComponent;
/**
* <p>Converts a simple object to a Query String representation.</p>
* <p>Nested objects, Arrays, and so on, are not supported.</p>
*
* @method stringify
* @for QueryString
* @public
* @submodule querystring-stringify-simple
* @param obj {Object} A single-level object to convert to a querystring.
* @param cfg {Object} (optional) Configuration object. In the simple
* module, only the arrayKey setting is
* supported. When set to true, the key of an
* array will have the '[]' notation appended
* to the key;.
* @static
*/
QueryString.stringify = function (obj, c) {
var qs = [],
// Default behavior is false; standard key notation.
s = c && c.arrayKey ? true : false,
key, i, l;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (Y.Lang.isArray(obj[key])) {
for (i = 0, l = obj[key].length; i < l; i++) {
qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i]));
}
}
else {
qs.push(EUC(key) + '=' + EUC(obj[key]));
}
}
}
return qs.join('&');
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('io-base', function(Y) {
/**
Base IO functionality. Provides basic XHR transport support.
@module io-base
@main io-base
@for IO
**/
var // List of events that comprise the IO event lifecycle.
EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'],
// Whitelist of used XHR response object properties.
XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'],
win = Y.config.win,
uid = 0;
/**
The IO class is a utility that brokers HTTP requests through a simplified
interface. Specifically, it allows JavaScript to make HTTP requests to
a resource without a page reload. The underlying transport for making
same-domain requests is the XMLHttpRequest object. IO can also use
Flash, if specified as a transport, for cross-domain requests.
@class IO
@constructor
@param {Object} config Object of EventTarget's publish method configurations
used to configure IO's events.
**/
function IO (config) {
var io = this;
io._uid = 'io:' + uid++;
io._init(config);
Y.io._map[io._uid] = io;
}
IO.prototype = {
//--------------------------------------
// Properties
//--------------------------------------
/**
* A counter that increments for each transaction.
*
* @property _id
* @private
* @type {Number}
*/
_id: 0,
/**
* Object of IO HTTP headers sent with each transaction.
*
* @property _headers
* @private
* @type {Object}
*/
_headers: {
'X-Requested-With' : 'XMLHttpRequest'
},
/**
* Object that stores timeout values for any transaction with a defined
* "timeout" configuration property.
*
* @property _timeout
* @private
* @type {Object}
*/
_timeout: {},
//--------------------------------------
// Methods
//--------------------------------------
_init: function(config) {
var io = this, i, len;
io.cfg = config || {};
Y.augment(io, Y.EventTarget);
for (i = 0, len = EVENTS.length; i < len; ++i) {
// Publish IO global events with configurations, if any.
// IO global events are set to broadcast by default.
// These events use the "io:" namespace.
io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config));
// Publish IO transaction events with configurations, if
// any. These events use the "io-trn:" namespace.
io.publish('io-trn:' + EVENTS[i], config);
}
},
/**
* Method that creates a unique transaction object for each request.
*
* @method _create
* @private
* @param {Object} cfg Configuration object subset to determine if
* the transaction is an XDR or file upload,
* requiring an alternate transport.
* @param {Number} id Transaction id
* @return {Object} The transaction object
*/
_create: function(config, id) {
var io = this,
transaction = {
id : Y.Lang.isNumber(id) ? id : io._id++,
uid: io._uid
},
alt = config.xdr ? config.xdr.use : null,
form = config.form && config.form.upload ? 'iframe' : null,
use;
if (alt === 'native') {
// Non-IE can use XHR level 2 and not rely on an
// external transport.
alt = Y.UA.ie ? 'xdr' : null;
}
use = alt || form;
transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) :
Y.merge(Y.IO.defaultTransport(), transaction);
if (transaction.notify) {
config.notify = function (e, t, c) { io.notify(e, t, c); };
}
if (!use) {
if (win && win.FormData && config.data instanceof FormData) {
transaction.c.upload.onprogress = function (e) {
io.progress(transaction, e, config);
};
transaction.c.onload = function (e) {
io.load(transaction, e, config);
};
transaction.c.onerror = function (e) {
io.error(transaction, e, config);
};
transaction.upload = true;
}
}
return transaction;
},
_destroy: function(transaction) {
if (win && !transaction.notify && !transaction.xdr) {
if (XHR && !transaction.upload) {
transaction.c.onreadystatechange = null;
} else if (transaction.upload) {
transaction.c.upload.onprogress = null;
transaction.c.onload = null;
transaction.c.onerror = null;
} else if (Y.UA.ie && !transaction.e) {
// IE, when using XMLHttpRequest as an ActiveX Object, will throw
// a "Type Mismatch" error if the event handler is set to "null".
transaction.c.abort();
}
}
transaction = transaction.c = null;
},
/**
* Method for creating and firing events.
*
* @method _evt
* @private
* @param {String} eventName Event to be published.
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration data subset for event subscription.
*/
_evt: function(eventName, transaction, config) {
var io = this, params,
args = config['arguments'],
emitFacade = io.cfg.emitFacade,
globalEvent = "io:" + eventName,
trnEvent = "io-trn:" + eventName;
// Workaround for #2532107
this.detach(trnEvent);
if (transaction.e) {
transaction.c = { status: 0, statusText: transaction.e };
}
// Fire event with parameters or an Event Facade.
params = [ emitFacade ?
{
id: transaction.id,
data: transaction.c,
cfg: config,
'arguments': args
} :
transaction.id
];
if (!emitFacade) {
if (eventName === EVENTS[0] || eventName === EVENTS[2]) {
if (args) {
params.push(args);
}
} else {
if (transaction.evt) {
params.push(transaction.evt);
} else {
params.push(transaction.c);
}
if (args) {
params.push(args);
}
}
}
params.unshift(globalEvent);
// Fire global events.
io.fire.apply(io, params);
// Fire transaction events, if receivers are defined.
if (config.on) {
params[0] = trnEvent;
io.once(trnEvent, config.on[eventName], config.context || Y);
io.fire.apply(io, params);
}
},
/**
* Fires event "io:start" and creates, fires a transaction-specific
* start event, if `config.on.start` is defined.
*
* @method start
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
start: function(transaction, config) {
/**
* Signals the start of an IO request.
* @event io:start
*/
this._evt(EVENTS[0], transaction, config);
},
/**
* Fires event "io:complete" and creates, fires a
* transaction-specific "complete" event, if config.on.complete is
* defined.
*
* @method complete
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
complete: function(transaction, config) {
/**
* Signals the completion of the request-response phase of a
* transaction. Response status and data are accessible, if
* available, in this event.
* @event io:complete
*/
this._evt(EVENTS[1], transaction, config);
},
/**
* Fires event "io:end" and creates, fires a transaction-specific "end"
* event, if config.on.end is defined.
*
* @method end
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
end: function(transaction, config) {
/**
* Signals the end of the transaction lifecycle.
* @event io:end
*/
this._evt(EVENTS[2], transaction, config);
this._destroy(transaction);
},
/**
* Fires event "io:success" and creates, fires a transaction-specific
* "success" event, if config.on.success is defined.
*
* @method success
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
success: function(transaction, config) {
/**
* Signals an HTTP response with status in the 2xx range.
* Fires after io:complete.
* @event io:success
*/
this._evt(EVENTS[3], transaction, config);
this.end(transaction, config);
},
/**
* Fires event "io:failure" and creates, fires a transaction-specific
* "failure" event, if config.on.failure is defined.
*
* @method failure
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
failure: function(transaction, config) {
/**
* Signals an HTTP response with status outside of the 2xx range.
* Fires after io:complete.
* @event io:failure
*/
this._evt(EVENTS[4], transaction, config);
this.end(transaction, config);
},
/**
* Fires event "io:progress" and creates, fires a transaction-specific
* "progress" event -- for XMLHttpRequest file upload -- if
* config.on.progress is defined.
*
* @method progress
* @param {Object} transaction Transaction object.
* @param {Object} progress event.
* @param {Object} config Configuration object for the transaction.
*/
progress: function(transaction, e, config) {
/**
* Signals the interactive state during a file upload transaction.
* This event fires after io:start and before io:complete.
* @event io:progress
*/
transaction.evt = e;
this._evt(EVENTS[5], transaction, config);
},
/**
* Fires event "io:complete" and creates, fires a transaction-specific
* "complete" event -- for XMLHttpRequest file upload -- if
* config.on.complete is defined.
*
* @method load
* @param {Object} transaction Transaction object.
* @param {Object} load event.
* @param {Object} config Configuration object for the transaction.
*/
load: function (transaction, e, config) {
transaction.evt = e.target;
this._evt(EVENTS[1], transaction, config);
},
/**
* Fires event "io:failure" and creates, fires a transaction-specific
* "failure" event -- for XMLHttpRequest file upload -- if
* config.on.failure is defined.
*
* @method error
* @param {Object} transaction Transaction object.
* @param {Object} error event.
* @param {Object} config Configuration object for the transaction.
*/
error: function (transaction, e, config) {
transaction.evt = e;
this._evt(EVENTS[4], transaction, config);
},
/**
* Retry an XDR transaction, using the Flash tranport, if the native
* transport fails.
*
* @method _retry
* @private
* @param {Object} transaction Transaction object.
* @param {String} uri Qualified path to transaction resource.
* @param {Object} config Configuration object for the transaction.
*/
_retry: function(transaction, uri, config) {
this._destroy(transaction);
config.xdr.use = 'flash';
return this.send(uri, config, transaction.id);
},
/**
* Method that concatenates string data for HTTP GET transactions.
*
* @method _concat
* @private
* @param {String} uri URI or root data.
* @param {String} data Data to be concatenated onto URI.
* @return {String}
*/
_concat: function(uri, data) {
uri += (uri.indexOf('?') === -1 ? '?' : '&') + data;
return uri;
},
/**
* Stores default client headers for all transactions. If a label is
* passed with no value argument, the header will be deleted.
*
* @method setHeader
* @param {String} name HTTP header
* @param {String} value HTTP header value
*/
setHeader: function(name, value) {
if (value) {
this._headers[name] = value;
} else {
delete this._headers[name];
}
},
/**
* Method that sets all HTTP headers to be sent in a transaction.
*
* @method _setHeaders
* @private
* @param {Object} transaction - XHR instance for the specific transaction.
* @param {Object} headers - HTTP headers for the specific transaction, as
* defined in the configuration object passed to YUI.io().
*/
_setHeaders: function(transaction, headers) {
headers = Y.merge(this._headers, headers);
Y.Object.each(headers, function(value, name) {
if (value !== 'disable') {
transaction.setRequestHeader(name, headers[name]);
}
});
},
/**
* Starts timeout count if the configuration object has a defined
* timeout property.
*
* @method _startTimeout
* @private
* @param {Object} transaction Transaction object generated by _create().
* @param {Object} timeout Timeout in milliseconds.
*/
_startTimeout: function(transaction, timeout) {
var io = this;
io._timeout[transaction.id] = setTimeout(function() {
io._abort(transaction, 'timeout');
}, timeout);
},
/**
* Clears the timeout interval started by _startTimeout().
*
* @method _clearTimeout
* @private
* @param {Number} id - Transaction id.
*/
_clearTimeout: function(id) {
clearTimeout(this._timeout[id]);
delete this._timeout[id];
},
/**
* Method that determines if a transaction response qualifies as success
* or failure, based on the response HTTP status code, and fires the
* appropriate success or failure events.
*
* @method _result
* @private
* @static
* @param {Object} transaction Transaction object generated by _create().
* @param {Object} config Configuration object passed to io().
*/
_result: function(transaction, config) {
var status;
// Firefox will throw an exception if attempting to access
// an XHR object's status property, after a request is aborted.
try {
status = transaction.c.status;
} catch(e) {
status = 0;
}
// IE reports HTTP 204 as HTTP 1223.
if (status >= 200 && status < 300 || status === 304 || status === 1223) {
this.success(transaction, config);
} else {
this.failure(transaction, config);
}
},
/**
* Event handler bound to onreadystatechange.
*
* @method _rS
* @private
* @param {Object} transaction Transaction object generated by _create().
* @param {Object} config Configuration object passed to YUI.io().
*/
_rS: function(transaction, config) {
var io = this;
if (transaction.c.readyState === 4) {
if (config.timeout) {
io._clearTimeout(transaction.id);
}
// Yield in the event of request timeout or abort.
setTimeout(function() {
io.complete(transaction, config);
io._result(transaction, config);
}, 0);
}
},
/**
* Terminates a transaction due to an explicit abort or timeout.
*
* @method _abort
* @private
* @param {Object} transaction Transaction object generated by _create().
* @param {String} type Identifies timed out or aborted transaction.
*/
_abort: function(transaction, type) {
if (transaction && transaction.c) {
transaction.e = type;
transaction.c.abort();
}
},
/**
* Requests a transaction. `send()` is implemented as `Y.io()`. Each
* transaction may include a configuration object. Its properties are:
*
* <dl>
* <dt>method</dt>
* <dd>HTTP method verb (e.g., GET or POST). If this property is not
* not defined, the default value will be GET.</dd>
*
* <dt>data</dt>
* <dd>This is the name-value string that will be sent as the
* transaction data. If the request is HTTP GET, the data become
* part of querystring. If HTTP POST, the data are sent in the
* message body.</dd>
*
* <dt>xdr</dt>
* <dd>Defines the transport to be used for cross-domain requests.
* By setting this property, the transaction will use the specified
* transport instead of XMLHttpRequest. The properties of the
* transport object are:
* <dl>
* <dt>use</dt>
* <dd>The transport to be used: 'flash' or 'native'</dd>
* <dt>dataType</dt>
* <dd>Set the value to 'XML' if that is the expected response
* content type.</dd>
* </dl></dd>
*
* <dt>form</dt>
* <dd>Form serialization configuration object. Its properties are:
* <dl>
* <dt>id</dt>
* <dd>Node object or id of HTML form</dd>
* <dt>useDisabled</dt>
* <dd>`true` to also serialize disabled form field values
* (defaults to `false`)</dd>
* </dl></dd>
*
* <dt>on</dt>
* <dd>Assigns transaction event subscriptions. Available events are:
* <dl>
* <dt>start</dt>
* <dd>Fires when a request is sent to a resource.</dd>
* <dt>complete</dt>
* <dd>Fires when the transaction is complete.</dd>
* <dt>success</dt>
* <dd>Fires when the HTTP response status is within the 2xx
* range.</dd>
* <dt>failure</dt>
* <dd>Fires when the HTTP response status is outside the 2xx
* range, if an exception occurs, if the transation is aborted,
* or if the transaction exceeds a configured `timeout`.</dd>
* <dt>end</dt>
* <dd>Fires at the conclusion of the transaction
* lifecycle, after `success` or `failure`.</dd>
* </dl>
*
* <p>Callback functions for `start` and `end` receive the id of the
* transaction as a first argument. For `complete`, `success`, and
* `failure`, callbacks receive the id and the response object
* (usually the XMLHttpRequest instance). If the `arguments`
* property was included in the configuration object passed to
* `Y.io()`, the configured data will be passed to all callbacks as
* the last argument.</p>
* </dd>
*
* <dt>sync</dt>
* <dd>Pass `true` to make a same-domain transaction synchronous.
* <strong>CAVEAT</strong>: This will negatively impact the user
* experience. Have a <em>very</em> good reason if you intend to use
* this.</dd>
*
* <dt>context</dt>
* <dd>The "`this'" object for all configured event handlers. If a
* specific context is needed for individual callbacks, bind the
* callback to a context using `Y.bind()`.</dd>
*
* <dt>headers</dt>
* <dd>Object map of transaction headers to send to the server. The
* object keys are the header names and the values are the header
* values.</dd>
*
* <dt>timeout</dt>
* <dd>Millisecond threshold for the transaction before being
* automatically aborted.</dd>
*
* <dt>arguments</dt>
* <dd>User-defined data passed to all registered event handlers.
* This value is available as the second argument in the "start" and
* "end" event handlers. It is the third argument in the "complete",
* "success", and "failure" event handlers. <strong>Be sure to quote
* this property name in the transaction configuration as
* "arguments" is a reserved word in JavaScript</strong> (e.g.
* `Y.io({ ..., "arguments": stuff })`).</dd>
* </dl>
*
* @method send
* @public
* @param {String} uri Qualified path to transaction resource.
* @param {Object} config Configuration object for the transaction.
* @param {Number} id Transaction id, if already set.
* @return {Object}
*/
send: function(uri, config, id) {
var transaction, method, i, len, sync, data,
io = this,
u = uri,
response = {};
config = config ? Y.Object(config) : {};
transaction = io._create(config, id);
method = config.method ? config.method.toUpperCase() : 'GET';
sync = config.sync;
data = config.data;
// Serialize an map object into a key-value string using
// querystring-stringify-simple.
if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) {
data = Y.QueryString.stringify(data);
}
if (config.form) {
if (config.form.upload) {
// This is a file upload transaction, calling
// upload() in io-upload-iframe.
return io.upload(transaction, uri, config);
} else {
// Serialize HTML form data into a key-value string.
data = io._serialize(config.form, data);
}
}
if (data) {
switch (method) {
case 'GET':
case 'HEAD':
case 'DELETE':
u = io._concat(u, data);
data = '';
Y.log('HTTP' + method + ' with data. The querystring is: ' + u, 'info', 'io');
break;
case 'POST':
case 'PUT':
// If Content-Type is defined in the configuration object, or
// or as a default header, it will be used instead of
// 'application/x-www-form-urlencoded; charset=UTF-8'
config.headers = Y.merge({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}, config.headers);
break;
}
}
if (transaction.xdr) {
// Route data to io-xdr module for flash and XDomainRequest.
return io.xdr(u, transaction, config);
}
else if (transaction.notify) {
// Route data to custom transport
return transaction.c.send(transaction, uri, config);
}
if (!sync && !transaction.upload) {
transaction.c.onreadystatechange = function() {
io._rS(transaction, config);
};
}
try {
// Determine if request is to be set as
// synchronous or asynchronous.
transaction.c.open(method, u, !sync, config.username || null, config.password || null);
io._setHeaders(transaction.c, config.headers || {});
io.start(transaction, config);
// Will work only in browsers that implement the
// Cross-Origin Resource Sharing draft.
if (config.xdr && config.xdr.credentials) {
if (!Y.UA.ie) {
transaction.c.withCredentials = true;
}
}
// Using "null" with HTTP POST will result in a request
// with no Content-Length header defined.
transaction.c.send(data);
if (sync) {
// Create a response object for synchronous transactions,
// mixing id and arguments properties with the xhr
// properties whitelist.
for (i = 0, len = XHR_PROPS.length; i < len; ++i) {
response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]];
}
response.getAllResponseHeaders = function() {
return transaction.c.getAllResponseHeaders();
};
response.getResponseHeader = function(name) {
return transaction.c.getResponseHeader(name);
};
io.complete(transaction, config);
io._result(transaction, config);
return response;
}
} catch(e) {
if (transaction.xdr) {
// This exception is usually thrown by browsers
// that do not support XMLHttpRequest Level 2.
// Retry the request with the XDR transport set
// to 'flash'. If the Flash transport is not
// initialized or available, the transaction
// will resolve to a transport error.
return io._retry(transaction, uri, config);
} else {
io.complete(transaction, config);
io._result(transaction, config);
}
}
// If config.timeout is defined, and the request is standard XHR,
// initialize timeout polling.
if (config.timeout) {
io._startTimeout(transaction, config.timeout);
Y.log('Configuration timeout set to: ' + config.timeout, 'info', 'io');
}
return {
id: transaction.id,
abort: function() {
return transaction.c ? io._abort(transaction, 'abort') : false;
},
isInProgress: function() {
return transaction.c ? (transaction.c.readyState % 4) : false;
},
io: io
};
}
};
/**
Method for initiating an ajax call. The first argument is the url end
point for the call. The second argument is an object to configure the
transaction and attach event subscriptions. The configuration object
supports the following properties:
<dl>
<dt>method</dt>
<dd>HTTP method verb (e.g., GET or POST). If this property is not
not defined, the default value will be GET.</dd>
<dt>data</dt>
<dd>This is the name-value string that will be sent as the
transaction data. If the request is HTTP GET, the data become
part of querystring. If HTTP POST, the data are sent in the
message body.</dd>
<dt>xdr</dt>
<dd>Defines the transport to be used for cross-domain requests.
By setting this property, the transaction will use the specified
transport instead of XMLHttpRequest. The properties of the
transport object are:
<dl>
<dt>use</dt>
<dd>The transport to be used: 'flash' or 'native'</dd>
<dt>dataType</dt>
<dd>Set the value to 'XML' if that is the expected response
content type.</dd>
</dl></dd>
<dt>form</dt>
<dd>Form serialization configuration object. Its properties are:
<dl>
<dt>id</dt>
<dd>Node object or id of HTML form</dd>
<dt>useDisabled</dt>
<dd>`true` to also serialize disabled form field values
(defaults to `false`)</dd>
</dl></dd>
<dt>on</dt>
<dd>Assigns transaction event subscriptions. Available events are:
<dl>
<dt>start</dt>
<dd>Fires when a request is sent to a resource.</dd>
<dt>complete</dt>
<dd>Fires when the transaction is complete.</dd>
<dt>success</dt>
<dd>Fires when the HTTP response status is within the 2xx
range.</dd>
<dt>failure</dt>
<dd>Fires when the HTTP response status is outside the 2xx
range, if an exception occurs, if the transation is aborted,
or if the transaction exceeds a configured `timeout`.</dd>
<dt>end</dt>
<dd>Fires at the conclusion of the transaction
lifecycle, after `success` or `failure`.</dd>
</dl>
<p>Callback functions for `start` and `end` receive the id of the
transaction as a first argument. For `complete`, `success`, and
`failure`, callbacks receive the id and the response object
(usually the XMLHttpRequest instance). If the `arguments`
property was included in the configuration object passed to
`Y.io()`, the configured data will be passed to all callbacks as
the last argument.</p>
</dd>
<dt>sync</dt>
<dd>Pass `true` to make a same-domain transaction synchronous.
<strong>CAVEAT</strong>: This will negatively impact the user
experience. Have a <em>very</em> good reason if you intend to use
this.</dd>
<dt>context</dt>
<dd>The "`this'" object for all configured event handlers. If a
specific context is needed for individual callbacks, bind the
callback to a context using `Y.bind()`.</dd>
<dt>headers</dt>
<dd>Object map of transaction headers to send to the server. The
object keys are the header names and the values are the header
values.</dd>
<dt>timeout</dt>
<dd>Millisecond threshold for the transaction before being
automatically aborted.</dd>
<dt>arguments</dt>
<dd>User-defined data passed to all registered event handlers.
This value is available as the second argument in the "start" and
"end" event handlers. It is the third argument in the "complete",
"success", and "failure" event handlers. <strong>Be sure to quote
this property name in the transaction configuration as
"arguments" is a reserved word in JavaScript</strong> (e.g.
`Y.io({ ..., "arguments": stuff })`).</dd>
</dl>
@method io
@static
@param {String} url qualified path to transaction resource.
@param {Object} config configuration object for the transaction.
@return {Object}
@for YUI
**/
Y.io = function(url, config) {
// Calling IO through the static interface will use and reuse
// an instance of IO.
var transaction = Y.io._map['io:0'] || new IO();
return transaction.send.apply(transaction, [url, config]);
};
/**
Method for setting and deleting IO HTTP headers to be sent with every
request.
Hosted as a property on the `io` function (e.g. `Y.io.header`).
@method header
@param {String} name HTTP header
@param {String} value HTTP header value
@static
**/
Y.io.header = function(name, value) {
// Calling IO through the static interface will use and reuse
// an instance of IO.
var transaction = Y.io._map['io:0'] || new IO();
transaction.setHeader(name, value);
};
Y.IO = IO;
// Map of all IO instances created.
Y.io._map = {};
var XHR = win && win.XMLHttpRequest,
XDR = win && win.XDomainRequest,
AX = win && win.ActiveXObject;
Y.mix(Y.IO, {
/**
* The ID of the default IO transport, defaults to `xhr`
* @property _default
* @type {String}
* @static
*/
_default: 'xhr',
/**
*
* @method defaultTransport
* @static
* @param {String} [id] The transport to set as the default, if empty a new transport is created.
* @return {Object} The transport object with a `send` method
*/
defaultTransport: function(id) {
if (id) {
Y.log('Setting default IO to: ' + id, 'info', 'io');
Y.IO._default = id;
} else {
var o = {
c: Y.IO.transports[Y.IO._default](),
notify: Y.IO._default === 'xhr' ? false : true
};
Y.log('Creating default transport: ' + Y.IO._default, 'info', 'io');
return o;
}
},
/**
* An object hash of custom transports available to IO
* @property transports
* @type {Object}
* @static
*/
transports: {
xhr: function () {
return XHR ? new XMLHttpRequest() :
AX ? new ActiveXObject('Microsoft.XMLHTTP') : null;
},
xdr: function () {
return XDR ? new XDomainRequest() : null;
},
iframe: function () { return {}; },
flash: null,
nodejs: null
},
/**
* Create a custom transport of type and return it's object
* @method customTransport
* @param {String} id The id of the transport to create.
* @static
*/
customTransport: function(id) {
var o = { c: Y.IO.transports[id]() };
o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true;
return o;
}
});
Y.mix(Y.IO.prototype, {
/**
* Fired from the notify method of the transport which in turn fires
* the event on the IO object.
* @method notify
* @param {String} event The name of the event
* @param {Object} transaction The transaction object
* @param {Object} config The configuration object for this transaction
*/
notify: function(event, transaction, config) {
var io = this;
switch (event) {
case 'timeout':
case 'abort':
case 'transport error':
transaction.c = { status: 0, statusText: event };
event = 'failure';
default:
io[event].apply(io, [transaction, config]);
}
}
});
}, '@VERSION@' ,{requires:['event-custom-base', 'querystring-stringify-simple']});
YUI.add('json-parse', function(Y) {
/**
* <p>The JSON module adds support for serializing JavaScript objects into
* JSON strings and parsing JavaScript objects from strings in JSON format.</p>
*
* <p>The JSON namespace is added to your YUI instance including static methods
* Y.JSON.parse(..) and Y.JSON.stringify(..).</p>
*
* <p>The functionality and method signatures follow the ECMAScript 5
* specification. In browsers with native JSON support, the native
* implementation is used.</p>
*
* <p>The <code>json</code> module is a rollup of <code>json-parse</code> and
* <code>json-stringify</code>.</p>
*
* <p>As their names suggest, <code>json-parse</code> adds support for parsing
* JSON data (Y.JSON.parse) and <code>json-stringify</code> for serializing
* JavaScript data into JSON strings (Y.JSON.stringify). You may choose to
* include either of the submodules individually if you don't need the
* complementary functionality, or include the rollup for both.</p>
*
* @module json
* @main json
* @class JSON
* @static
*/
/**
* Provides Y.JSON.parse method to accept JSON strings and return native
* JavaScript objects.
*
* @module json
* @submodule json-parse
* @for JSON
* @static
*/
// All internals kept private for security reasons
function fromGlobal(ref) {
return (Y.config.win || this || {})[ref];
}
/**
* Alias to native browser implementation of the JSON object if available.
*
* @property Native
* @type {Object}
* @private
*/
var _JSON = fromGlobal('JSON'),
Native = (Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON),
useNative = !!Native,
/**
* Replace certain Unicode characters that JavaScript may handle incorrectly
* during eval--either by deleting them or treating them as line
* endings--with escape sequences.
* IMPORTANT NOTE: This regex will be used to modify the input if a match is
* found.
*
* @property _UNICODE_EXCEPTIONS
* @type {RegExp}
* @private
*/
_UNICODE_EXCEPTIONS = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
/**
* First step in the safety evaluation. Regex used to replace all escape
* sequences (i.e. "\\", etc) with '@' characters (a non-JSON character).
*
* @property _ESCAPES
* @type {RegExp}
* @private
*/
_ESCAPES = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
/**
* Second step in the safety evaluation. Regex used to replace all simple
* values with ']' characters.
*
* @property _VALUES
* @type {RegExp}
* @private
*/
_VALUES = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
/**
* Third step in the safety evaluation. Regex used to remove all open
* square brackets following a colon, comma, or at the beginning of the
* string.
*
* @property _BRACKETS
* @type {RegExp}
* @private
*/
_BRACKETS = /(?:^|:|,)(?:\s*\[)+/g,
/**
* Final step in the safety evaluation. Regex used to test the string left
* after all previous replacements for invalid characters.
*
* @property _UNSAFE
* @type {RegExp}
* @private
*/
_UNSAFE = /[^\],:{}\s]/,
/**
* Replaces specific unicode characters with their appropriate \unnnn
* format. Some browsers ignore certain characters during eval.
*
* @method escapeException
* @param c {String} Unicode character
* @return {String} the \unnnn escapement of the character
* @private
*/
_escapeException = function (c) {
return '\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4);
},
/**
* Traverses nested objects, applying a reviver function to each (key,value)
* from the scope if the key:value's containing object. The value returned
* from the function will replace the original value in the key:value pair.
* If the value returned is undefined, the key will be omitted from the
* returned object.
*
* @method _revive
* @param data {MIXED} Any JavaScript data
* @param reviver {Function} filter or mutation function
* @return {MIXED} The results of the filtered data
* @private
*/
_revive = function (data, reviver) {
var walk = function (o,key) {
var k,v,value = o[key];
if (value && typeof value === 'object') {
for (k in value) {
if (value.hasOwnProperty(k)) {
v = walk(value, k);
if (v === undefined) {
delete value[k];
} else {
value[k] = v;
}
}
}
}
return reviver.call(o,key,value);
};
return typeof reviver === 'function' ? walk({'':data},'') : data;
},
/**
* Parse a JSON string, returning the native JavaScript representation.
*
* @param s {string} JSON string data
* @param reviver {function} (optional) function(k,v) passed each key value
* pair of object literals, allowing pruning or altering values
* @return {MIXED} the native JavaScript representation of the JSON string
* @throws SyntaxError
* @method parse
* @static
*/
// JavaScript implementation in lieu of native browser support. Based on
// the json2.js library from http://json.org
_parse = function (s,reviver) {
// Replace certain Unicode characters that are otherwise handled
// incorrectly by some browser implementations.
// NOTE: This modifies the input if such characters are found!
s = s.replace(_UNICODE_EXCEPTIONS, _escapeException);
// Test for any remaining invalid characters
if (!_UNSAFE.test(s.replace(_ESCAPES,'@').
replace(_VALUES,']').
replace(_BRACKETS,''))) {
// Eval the text into a JavaScript data structure, apply any
// reviver function, and return
return _revive( eval('(' + s + ')'), reviver );
}
throw new SyntaxError('JSON.parse');
};
Y.namespace('JSON').parse = function (s,reviver) {
if (typeof s !== 'string') {
s += '';
}
return Native && Y.JSON.useNativeParse ?
Native.parse(s,reviver) : _parse(s,reviver);
};
function workingNative( k, v ) {
return k === "ok" ? true : v;
}
// Double check basic functionality. This is mainly to catch early broken
// implementations of the JSON API in Firefox 3.1 beta1 and beta2
if ( Native ) {
try {
useNative = ( Native.parse( '{"ok":false}', workingNative ) ).ok;
}
catch ( e ) {
useNative = false;
}
}
/**
* Leverage native JSON parse if the browser has a native implementation.
* In general, this is a good idea. See the Known Issues section in the
* JSON user guide for caveats. The default value is true for browsers with
* native JSON support.
*
* @property useNativeParse
* @type Boolean
* @default true
* @static
*/
Y.JSON.useNativeParse = useNative;
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('transition', function(Y) {
/**
* Provides the transition method for Node.
* Transition has no API of its own, but adds the transition method to Node.
*
* @module transition
* @requires node-style
*/
var CAMEL_VENDOR_PREFIX = '',
VENDOR_PREFIX = '',
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
TRANSITION = 'transition',
TRANSITION_CAMEL = 'Transition',
TRANSITION_PROPERTY_CAMEL,
TRANSITION_PROPERTY,
TRANSITION_DURATION,
TRANSITION_TIMING_FUNCTION,
TRANSITION_DELAY,
TRANSITION_END,
ON_TRANSITION_END,
TRANSFORM_CAMEL,
EMPTY_OBJ = {},
VENDORS = [
'Webkit',
'Moz'
],
VENDOR_TRANSITION_END = {
Webkit: 'webkitTransitionEnd'
},
/**
* A class for constructing transition instances.
* Adds the "transition" method to Node.
* @class Transition
* @constructor
*/
Transition = function() {
this.init.apply(this, arguments);
};
Transition._toCamel = function(property) {
property = property.replace(/-([a-z])/gi, function(m0, m1) {
return m1.toUpperCase();
});
return property;
};
Transition._toHyphen = function(property) {
property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) {
var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2;
if (m3) {
str += '-' + m3.toLowerCase();
}
return str;
});
return property;
};
Transition.SHOW_TRANSITION = 'fadeIn';
Transition.HIDE_TRANSITION = 'fadeOut';
Transition.useNative = false;
Y.Array.each(VENDORS, function(val) { // then vendor specific
var property = val + TRANSITION_CAMEL;
if (property in DOCUMENT[DOCUMENT_ELEMENT].style) {
CAMEL_VENDOR_PREFIX = val;
VENDOR_PREFIX = Transition._toHyphen(val) + '-';
Transition.useNative = true;
Transition.supported = true; // TODO: remove
Transition._VENDOR_PREFIX = val;
}
});
TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + TRANSITION_CAMEL;
TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty';
TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property';
TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration';
TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function';
TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay';
TRANSITION_END = 'transitionend';
ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend';
TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END;
TRANSFORM_CAMEL = CAMEL_VENDOR_PREFIX + 'Transform';
Transition.fx = {};
Transition.toggles = {};
Transition._hasEnd = {};
Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i;
Y.Node.DOM_EVENTS[TRANSITION_END] = 1;
Transition.NAME = 'transition';
Transition.DEFAULT_EASING = 'ease';
Transition.DEFAULT_DURATION = 0.5;
Transition.DEFAULT_DELAY = 0;
Transition._nodeAttrs = {};
Transition.prototype = {
constructor: Transition,
init: function(node, config) {
var anim = this;
anim._node = node;
if (!anim._running && config) {
anim._config = config;
node._transition = anim; // cache for reuse
anim._duration = ('duration' in config) ?
config.duration: anim.constructor.DEFAULT_DURATION;
anim._delay = ('delay' in config) ?
config.delay: anim.constructor.DEFAULT_DELAY;
anim._easing = config.easing || anim.constructor.DEFAULT_EASING;
anim._count = 0; // track number of animated properties
anim._running = false;
}
return anim;
},
addProperty: function(prop, config) {
var anim = this,
node = this._node,
uid = Y.stamp(node),
nodeInstance = Y.one(node),
attrs = Transition._nodeAttrs[uid],
computed,
compareVal,
dur,
attr,
val;
if (!attrs) {
attrs = Transition._nodeAttrs[uid] = {};
}
attr = attrs[prop];
// might just be a value
if (config && config.value !== undefined) {
val = config.value;
} else if (config !== undefined) {
val = config;
config = EMPTY_OBJ;
}
if (typeof val === 'function') {
val = val.call(nodeInstance, nodeInstance);
}
if (attr && attr.transition) {
// take control if another transition owns this property
if (attr.transition !== anim) {
attr.transition._count--; // remapping attr to this transition
}
}
anim._count++; // properties per transition
// make 0 async and fire events
dur = ((typeof config.duration != 'undefined') ? config.duration :
anim._duration) || 0.0001;
attrs[prop] = {
value: val,
duration: dur,
delay: (typeof config.delay != 'undefined') ? config.delay :
anim._delay,
easing: config.easing || anim._easing,
transition: anim
};
// native end event doesnt fire when setting to same value
// supplementing with timer
// val may be a string or number (height: 0, etc), but computedStyle is always string
computed = Y.DOM.getComputedStyle(node, prop);
compareVal = (typeof val === 'string') ? computed : parseFloat(computed);
if (Transition.useNative && compareVal === val) {
setTimeout(function() {
anim._onNativeEnd.call(node, {
propertyName: prop,
elapsedTime: dur
});
}, dur * 1000);
}
},
removeProperty: function(prop) {
var anim = this,
attrs = Transition._nodeAttrs[Y.stamp(anim._node)];
if (attrs && attrs[prop]) {
delete attrs[prop];
anim._count--;
}
},
initAttrs: function(config) {
var attr,
node = this._node;
if (config.transform && !config[TRANSFORM_CAMEL]) {
config[TRANSFORM_CAMEL] = config.transform;
delete config.transform; // TODO: copy
}
for (attr in config) {
if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) {
this.addProperty(attr, config[attr]);
// when size is auto or % webkit starts from zero instead of computed
// (https://bugs.webkit.org/show_bug.cgi?id=16020)
// TODO: selective set
if (node.style[attr] === '') {
Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr));
}
}
}
},
/**
* Starts or an animation.
* @method run
* @chainable
* @private
*/
run: function(callback) {
var anim = this,
node = anim._node,
config = anim._config,
data = {
type: 'transition:start',
config: config
};
if (!anim._running) {
anim._running = true;
if (config.on && config.on.start) {
config.on.start.call(Y.one(node), data);
}
anim.initAttrs(anim._config);
anim._callback = callback;
anim._start();
}
return anim;
},
_start: function() {
this._runNative();
},
_prepDur: function(dur) {
dur = parseFloat(dur);
return dur + 's';
},
_runNative: function(time) {
var anim = this,
node = anim._node,
uid = Y.stamp(node),
style = node.style,
computed = node.ownerDocument.defaultView.getComputedStyle(node),
attrs = Transition._nodeAttrs[uid],
cssText = '',
cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)],
transitionText = TRANSITION_PROPERTY + ': ',
duration = TRANSITION_DURATION + ': ',
easing = TRANSITION_TIMING_FUNCTION + ': ',
delay = TRANSITION_DELAY + ': ',
hyphy,
attr,
name;
// preserve existing transitions
if (cssTransition !== 'all') {
transitionText += cssTransition + ',';
duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ',';
easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ',';
delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ',';
}
// run transitions mapped to this instance
for (name in attrs) {
hyphy = Transition._toHyphen(name);
attr = attrs[name];
if ((attr = attrs[name]) && attr.transition === anim) {
if (name in node.style) { // only native styles allowed
duration += anim._prepDur(attr.duration) + ',';
delay += anim._prepDur(attr.delay) + ',';
easing += (attr.easing) + ',';
transitionText += hyphy + ',';
cssText += hyphy + ': ' + attr.value + '; ';
} else {
this.removeProperty(name);
}
}
}
transitionText = transitionText.replace(/,$/, ';');
duration = duration.replace(/,$/, ';');
easing = easing.replace(/,$/, ';');
delay = delay.replace(/,$/, ';');
// only one native end event per node
if (!Transition._hasEnd[uid]) {
node.addEventListener(TRANSITION_END, anim._onNativeEnd, '');
Transition._hasEnd[uid] = true;
}
style.cssText += transitionText + duration + easing + delay + cssText;
},
_end: function(elapsed) {
var anim = this,
node = anim._node,
callback = anim._callback,
config = anim._config,
data = {
type: 'transition:end',
config: config,
elapsedTime: elapsed
},
nodeInstance = Y.one(node);
anim._running = false;
anim._callback = null;
if (node) {
if (config.on && config.on.end) {
setTimeout(function() { // IE: allow previous update to finish
config.on.end.call(nodeInstance, data);
// nested to ensure proper fire order
if (callback) {
callback.call(nodeInstance, data);
}
}, 1);
} else if (callback) {
setTimeout(function() { // IE: allow previous update to finish
callback.call(nodeInstance, data);
}, 1);
}
}
},
_endNative: function(name) {
var node = this._node,
value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)];
name = Transition._toHyphen(name);
if (typeof value === 'string') {
value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ',');
value = value.replace(/^,|,$/, '');
node.style[TRANSITION_CAMEL] = value;
}
},
_onNativeEnd: function(e) {
var node = this,
uid = Y.stamp(node),
event = e,//e._event,
name = Transition._toCamel(event.propertyName),
elapsed = event.elapsedTime,
attrs = Transition._nodeAttrs[uid],
attr = attrs[name],
anim = (attr) ? attr.transition : null,
data,
config;
if (anim) {
anim.removeProperty(name);
anim._endNative(name);
config = anim._config[name];
data = {
type: 'propertyEnd',
propertyName: name,
elapsedTime: elapsed,
config: config
};
if (config && config.on && config.on.end) {
config.on.end.call(Y.one(node), data);
}
if (anim._count <= 0) { // after propertyEnd fires
anim._end(elapsed);
node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style
}
}
},
destroy: function() {
var anim = this,
node = anim._node;
if (node) {
node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false);
anim._node = null;
}
}
};
Y.Transition = Transition;
Y.TransitionNative = Transition; // TODO: remove
/**
* Animate one or more css properties to a given value. Requires the "transition" module.
* <pre>example usage:
* Y.one('#demo').transition({
* duration: 1, // in seconds, default is 0.5
* easing: 'ease-out', // default is 'ease'
* delay: '1', // delay start for 1 second, default is 0
*
* height: '10px',
* width: '10px',
*
* opacity: { // per property
* value: 0,
* duration: 2,
* delay: 2,
* easing: 'ease-in'
* }
* });
* </pre>
* @for Node
* @method transition
* @param {Object} config An object containing one or more style properties, a duration and an easing.
* @param {Function} callback A function to run after the transition has completed.
* @chainable
*/
Y.Node.prototype.transition = function(name, config, callback) {
var
transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)],
anim = (transitionAttrs) ? transitionAttrs.transition || null : null,
fxConfig,
prop;
if (typeof name === 'string') { // named effect, pull config from registry
if (typeof config === 'function') {
callback = config;
config = null;
}
fxConfig = Transition.fx[name];
if (config && typeof config !== 'boolean') {
config = Y.clone(config);
for (prop in fxConfig) {
if (fxConfig.hasOwnProperty(prop)) {
if (! (prop in config)) {
config[prop] = fxConfig[prop];
}
}
}
} else {
config = fxConfig;
}
} else { // name is a config, config is a callback or undefined
callback = config;
config = name;
}
if (anim && !anim._running) {
anim.init(this, config);
} else {
anim = new Transition(this._node, config);
}
anim.run(callback);
return this;
};
Y.Node.prototype.show = function(name, config, callback) {
this._show(); // show prior to transition
if (name && Y.Transition) {
if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default
if (typeof config === 'function') {
callback = config;
config = name;
}
name = Transition.SHOW_TRANSITION;
}
this.transition(name, config, callback);
}
else if (name && !Y.Transition) { Y.log('unable to transition show; missing transition module', 'warn', 'node'); }
return this;
};
var _wrapCallBack = function(anim, fn, callback) {
return function() {
if (fn) {
fn.call(anim);
}
if (callback) {
callback.apply(anim._node, arguments);
}
};
};
Y.Node.prototype.hide = function(name, config, callback) {
if (name && Y.Transition) {
if (typeof config === 'function') {
callback = config;
config = null;
}
callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback
if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default
if (typeof config === 'function') {
callback = config;
config = name;
}
name = Transition.HIDE_TRANSITION;
}
this.transition(name, config, callback);
} else if (name && !Y.Transition) { Y.log('unable to transition hide; missing transition module', 'warn', 'node');
} else {
this._hide();
}
return this;
};
/**
* Animate one or more css properties to a given value. Requires the "transition" module.
* <pre>example usage:
* Y.all('.demo').transition({
* duration: 1, // in seconds, default is 0.5
* easing: 'ease-out', // default is 'ease'
* delay: '1', // delay start for 1 second, default is 0
*
* height: '10px',
* width: '10px',
*
* opacity: { // per property
* value: 0,
* duration: 2,
* delay: 2,
* easing: 'ease-in'
* }
* });
* </pre>
* @for NodeList
* @method transition
* @param {Object} config An object containing one or more style properties, a duration and an easing.
* @param {Function} callback A function to run after the transition has completed. The callback fires
* once per item in the NodeList.
* @chainable
*/
Y.NodeList.prototype.transition = function(config, callback) {
var nodes = this._nodes,
i = 0,
node;
while ((node = nodes[i++])) {
Y.one(node).transition(config, callback);
}
return this;
};
Y.Node.prototype.toggleView = function(name, on, callback) {
this._toggles = this._toggles || [];
callback = arguments[arguments.length - 1];
if (typeof name == 'boolean') { // no transition, just toggle
on = name;
name = null;
}
name = name || Y.Transition.DEFAULT_TOGGLE;
if (typeof on == 'undefined' && name in this._toggles) { // reverse current toggle
on = ! this._toggles[name];
}
on = (on) ? 1 : 0;
if (on) {
this._show();
} else {
callback = _wrapCallBack(this, this._hide, callback);
}
this._toggles[name] = on;
this.transition(Y.Transition.toggles[name][on], callback);
return this;
};
Y.NodeList.prototype.toggleView = function(name, on, callback) {
var nodes = this._nodes,
i = 0,
node;
while ((node = nodes[i++])) {
Y.one(node).toggleView(name, on, callback);
}
return this;
};
Y.mix(Transition.fx, {
fadeOut: {
opacity: 0,
duration: 0.5,
easing: 'ease-out'
},
fadeIn: {
opacity: 1,
duration: 0.5,
easing: 'ease-in'
},
sizeOut: {
height: 0,
width: 0,
duration: 0.75,
easing: 'ease-out'
},
sizeIn: {
height: function(node) {
return node.get('scrollHeight') + 'px';
},
width: function(node) {
return node.get('scrollWidth') + 'px';
},
duration: 0.5,
easing: 'ease-in',
on: {
start: function() {
var overflow = this.getStyle('overflow');
if (overflow !== 'hidden') { // enable scrollHeight/Width
this.setStyle('overflow', 'hidden');
this._transitionOverflow = overflow;
}
},
end: function() {
if (this._transitionOverflow) { // revert overridden value
this.setStyle('overflow', this._transitionOverflow);
delete this._transitionOverflow;
}
}
}
}
});
Y.mix(Transition.toggles, {
size: ['sizeOut', 'sizeIn'],
fade: ['fadeOut', 'fadeIn']
});
Transition.DEFAULT_TOGGLE = 'fade';
}, '@VERSION@' ,{requires:['node-style']});
YUI.add('selector-css2', function(Y) {
/**
* The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements.
* @module dom
* @submodule selector-css2
* @for Selector
*/
/*
* Provides helper methods for collecting and filtering DOM elements.
*/
var PARENT_NODE = 'parentNode',
TAG_NAME = 'tagName',
ATTRIBUTES = 'attributes',
COMBINATOR = 'combinator',
PSEUDOS = 'pseudos',
Selector = Y.Selector,
SelectorCSS2 = {
_reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/,
SORT_RESULTS: true,
// TODO: better detection, document specific
_isXML: (function() {
var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV');
return isXML;
}()),
/**
* Mapping of shorthand tokens to corresponding attribute selector
* @property shorthand
* @type object
*/
shorthand: {
'\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]',
'\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]'
},
/**
* List of operators and corresponding boolean functions.
* These functions are passed the attribute and the current node's value of the attribute.
* @property operators
* @type object
*/
operators: {
'': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute
'~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited
'|=': '^{val}-?' // optional hyphen-delimited
},
pseudos: {
'first-child': function(node) {
return Y.DOM._children(node[PARENT_NODE])[0] === node;
}
},
_bruteQuery: function(selector, root, firstOnly) {
var ret = [],
nodes = [],
tokens = Selector._tokenize(selector),
token = tokens[tokens.length - 1],
rootDoc = Y.DOM._getDoc(root),
child,
id,
className,
tagName;
if (token) {
// prefilter nodes
id = token.id;
className = token.className;
tagName = token.tagName || '*';
if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags
// try ID first, unless no root.all && root not in document
// (root.all works off document, but not getElementById)
if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) {
nodes = Y.DOM.allById(id, root);
// try className
} else if (className) {
nodes = root.getElementsByClassName(className);
} else { // default to tagName
nodes = root.getElementsByTagName(tagName);
}
} else { // brute getElementsByTagName()
child = root.firstChild;
while (child) {
// only collect HTMLElements
// match tag to supplement missing getElementsByTagName
if (child.tagName && (tagName === '*' || child.tagName === tagName)) {
nodes.push(child);
}
child = child.nextSibling || child.firstChild;
}
}
if (nodes.length) {
ret = Selector._filterNodes(nodes, tokens, firstOnly);
}
}
return ret;
},
_filterNodes: function(nodes, tokens, firstOnly) {
var i = 0,
j,
len = tokens.length,
n = len - 1,
result = [],
node = nodes[0],
tmpNode = node,
getters = Y.Selector.getters,
operator,
combinator,
token,
path,
pass,
value,
tests,
test;
for (i = 0; (tmpNode = node = nodes[i++]);) {
n = len - 1;
path = null;
testLoop:
while (tmpNode && tmpNode.tagName) {
token = tokens[n];
tests = token.tests;
j = tests.length;
if (j && !pass) {
while ((test = tests[--j])) {
operator = test[1];
if (getters[test[0]]) {
value = getters[test[0]](tmpNode, test[0]);
} else {
value = tmpNode[test[0]];
if (test[0] === 'tagName' && !Selector._isXML) {
value = value.toUpperCase();
}
if (typeof value != 'string' && value !== undefined && value.toString) {
value = value.toString(); // coerce for comparison
} else if (value === undefined && tmpNode.getAttribute) {
// use getAttribute for non-standard attributes
value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE
}
}
if ((operator === '=' && value !== test[2]) || // fast path for equality
(typeof operator !== 'string' && // protect against String.test monkey-patch (Moo)
operator.test && !operator.test(value)) || // regex test
(!operator.test && // protect against RegExp as function (webkit)
typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test
// skip non element nodes or non-matching tags
if ((tmpNode = tmpNode[path])) {
while (tmpNode &&
(!tmpNode.tagName ||
(token.tagName && token.tagName !== tmpNode.tagName))
) {
tmpNode = tmpNode[path];
}
}
continue testLoop;
}
}
}
n--; // move to next token
// now that we've passed the test, move up the tree by combinator
if (!pass && (combinator = token.combinator)) {
path = combinator.axis;
tmpNode = tmpNode[path];
// skip non element nodes
while (tmpNode && !tmpNode.tagName) {
tmpNode = tmpNode[path];
}
if (combinator.direct) { // one pass only
path = null;
}
} else { // success if we made it this far
result.push(node);
if (firstOnly) {
return result;
}
break;
}
}
}
node = tmpNode = null;
return result;
},
combinators: {
' ': {
axis: 'parentNode'
},
'>': {
axis: 'parentNode',
direct: true
},
'+': {
axis: 'previousSibling',
direct: true
}
},
_parsers: [
{
name: ATTRIBUTES,
re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i,
fn: function(match, token) {
var operator = match[2] || '',
operators = Selector.operators,
escVal = (match[3]) ? match[3].replace(/\\/g, '') : '',
test;
// add prefiltering for ID and CLASS
if ((match[1] === 'id' && operator === '=') ||
(match[1] === 'className' &&
Y.config.doc.documentElement.getElementsByClassName &&
(operator === '~=' || operator === '='))) {
token.prefilter = match[1];
match[3] = escVal;
// escape all but ID for prefilter, which may run through QSA (via Dom.allById)
token[match[1]] = (match[1] === 'id') ? match[3] : escVal;
}
// add tests
if (operator in operators) {
test = operators[operator];
if (typeof test === 'string') {
match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1');
test = new RegExp(test.replace('{val}', match[3]));
}
match[2] = test;
}
if (!token.last || token.prefilter !== match[1]) {
return match.slice(1);
}
}
},
{
name: TAG_NAME,
re: /^((?:-?[_a-z]+[\w-]*)|\*)/i,
fn: function(match, token) {
var tag = match[1];
if (!Selector._isXML) {
tag = tag.toUpperCase();
}
token.tagName = tag;
if (tag !== '*' && (!token.last || token.prefilter)) {
return [TAG_NAME, '=', tag];
}
if (!token.prefilter) {
token.prefilter = 'tagName';
}
}
},
{
name: COMBINATOR,
re: /^\s*([>+~]|\s)\s*/,
fn: function(match, token) {
}
},
{
name: PSEUDOS,
re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i,
fn: function(match, token) {
var test = Selector[PSEUDOS][match[1]];
if (test) { // reorder match array and unescape special chars for tests
if (match[2]) {
match[2] = match[2].replace(/\\/g, '');
}
return [match[2], test];
} else { // selector token not supported (possibly missing CSS3 module)
return false;
}
}
}
],
_getToken: function(token) {
return {
tagName: null,
id: null,
className: null,
attributes: {},
combinator: null,
tests: []
};
},
/*
Break selector into token units per simple selector.
Combinator is attached to the previous token.
*/
_tokenize: function(selector) {
selector = selector || '';
selector = Selector._parseSelector(Y.Lang.trim(selector));
var token = Selector._getToken(), // one token per simple selector (left selector holds combinator)
query = selector, // original query for debug report
tokens = [], // array of tokens
found = false, // whether or not any matches were found this pass
match, // the regex match
test,
i, parser;
/*
Search for selector patterns, store, and strip them from the selector string
until no patterns match (invalid selector) or we run out of chars.
Multiple attributes and pseudos are allowed, in any order.
for example:
'form:first-child[type=button]:not(button)[lang|=en]'
*/
outer:
do {
found = false; // reset after full pass
for (i = 0; (parser = Selector._parsers[i++]);) {
if ( (match = parser.re.exec(selector)) ) { // note assignment
if (parser.name !== COMBINATOR ) {
token.selector = selector;
}
selector = selector.replace(match[0], ''); // strip current match from selector
if (!selector.length) {
token.last = true;
}
if (Selector._attrFilters[match[1]]) { // convert class to className, etc.
match[1] = Selector._attrFilters[match[1]];
}
test = parser.fn(match, token);
if (test === false) { // selector not supported
found = false;
break outer;
} else if (test) {
token.tests.push(test);
}
if (!selector.length || parser.name === COMBINATOR) {
tokens.push(token);
token = Selector._getToken(token);
if (parser.name === COMBINATOR) {
token.combinator = Y.Selector.combinators[match[1]];
}
}
found = true;
}
}
} while (found && selector.length);
if (!found || selector.length) { // not fully parsed
Y.log('query: ' + query + ' contains unsupported token in: ' + selector, 'warn', 'Selector');
tokens = [];
}
return tokens;
},
_replaceMarkers: function(selector) {
selector = selector.replace(/\[/g, '\uE003');
selector = selector.replace(/\]/g, '\uE004');
selector = selector.replace(/\(/g, '\uE005');
selector = selector.replace(/\)/g, '\uE006');
return selector;
},
_replaceShorthand: function(selector) {
var shorthand = Y.Selector.shorthand,
re;
for (re in shorthand) {
if (shorthand.hasOwnProperty(re)) {
selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]);
}
}
return selector;
},
_parseSelector: function(selector) {
var replaced = Y.Selector._replaceSelector(selector),
selector = replaced.selector;
// replace shorthand (".foo, #bar") after pseudos and attrs
// to avoid replacing unescaped chars
selector = Y.Selector._replaceShorthand(selector);
selector = Y.Selector._restore('attr', selector, replaced.attrs);
selector = Y.Selector._restore('pseudo', selector, replaced.pseudos);
// replace braces and parens before restoring escaped chars
// to avoid replacing ecaped markers
selector = Y.Selector._replaceMarkers(selector);
selector = Y.Selector._restore('esc', selector, replaced.esc);
return selector;
},
_attrFilters: {
'class': 'className',
'for': 'htmlFor'
},
getters: {
href: function(node, attr) {
return Y.DOM.getAttribute(node, attr);
},
id: function(node, attr) {
return Y.DOM.getId(node);
}
}
};
Y.mix(Y.Selector, SelectorCSS2, true);
Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href;
// IE wants class with native queries
if (Y.Selector.useNative && Y.config.doc.querySelector) {
Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]';
}
}, '@VERSION@' ,{requires:['selector-native']});
YUI.add('selector-css3', function(Y) {
/**
* The selector css3 module provides support for css3 selectors.
* @module dom
* @submodule selector-css3
* @for Selector
*/
/*
an+b = get every _a_th node starting at the _b_th
0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element
1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n")
an+0 = get every _a_th element, "0" may be omitted
*/
Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/;
Y.Selector._getNth = function(node, expr, tag, reverse) {
Y.Selector._reNth.test(expr);
var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_)
n = RegExp.$2, // "n"
oddeven = RegExp.$3, // "odd" or "even"
b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_
result = [],
siblings = Y.DOM._children(node.parentNode, tag),
op;
if (oddeven) {
a = 2; // always every other
op = '+';
n = 'n';
b = (oddeven === 'odd') ? 1 : 0;
} else if ( isNaN(a) ) {
a = (n) ? 1 : 0; // start from the first or no repeat
}
if (a === 0) { // just the first
if (reverse) {
b = siblings.length - b + 1;
}
if (siblings[b - 1] === node) {
return true;
} else {
return false;
}
} else if (a < 0) {
reverse = !!reverse;
a = Math.abs(a);
}
if (!reverse) {
for (var i = b - 1, len = siblings.length; i < len; i += a) {
if ( i >= 0 && siblings[i] === node ) {
return true;
}
}
} else {
for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) {
if ( i < len && siblings[i] === node ) {
return true;
}
}
}
return false;
};
Y.mix(Y.Selector.pseudos, {
'root': function(node) {
return node === node.ownerDocument.documentElement;
},
'nth-child': function(node, expr) {
return Y.Selector._getNth(node, expr);
},
'nth-last-child': function(node, expr) {
return Y.Selector._getNth(node, expr, null, true);
},
'nth-of-type': function(node, expr) {
return Y.Selector._getNth(node, expr, node.tagName);
},
'nth-last-of-type': function(node, expr) {
return Y.Selector._getNth(node, expr, node.tagName, true);
},
'last-child': function(node) {
var children = Y.DOM._children(node.parentNode);
return children[children.length - 1] === node;
},
'first-of-type': function(node) {
return Y.DOM._children(node.parentNode, node.tagName)[0] === node;
},
'last-of-type': function(node) {
var children = Y.DOM._children(node.parentNode, node.tagName);
return children[children.length - 1] === node;
},
'only-child': function(node) {
var children = Y.DOM._children(node.parentNode);
return children.length === 1 && children[0] === node;
},
'only-of-type': function(node) {
var children = Y.DOM._children(node.parentNode, node.tagName);
return children.length === 1 && children[0] === node;
},
'empty': function(node) {
return node.childNodes.length === 0;
},
'not': function(node, expr) {
return !Y.Selector.test(node, expr);
},
'contains': function(node, expr) {
var text = node.innerText || node.textContent || '';
return text.indexOf(expr) > -1;
},
'checked': function(node) {
return (node.checked === true || node.selected === true);
},
enabled: function(node) {
return (node.disabled !== undefined && !node.disabled);
},
disabled: function(node) {
return (node.disabled);
}
});
Y.mix(Y.Selector.operators, {
'^=': '^{val}', // Match starts with value
'$=': '{val}$', // Match ends with value
'*=': '{val}' // Match contains value as substring
});
Y.Selector.combinators['~'] = {
axis: 'previousSibling'
};
}, '@VERSION@' ,{requires:['selector-native', 'selector-css2']});
YUI.add('yui-log', function(Y) {
/**
* Provides console log capability and exposes a custom event for
* console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-log
*/
var INSTANCE = Y,
LOGEVENT = 'yui:log',
UNDEFINED = 'undefined',
LEVELS = { debug: 1,
info: 1,
warn: 1,
error: 1 };
/**
* If the 'debug' config is true, a 'yui:log' event will be
* dispatched, which the Console widget and anything else
* can consume. If the 'useBrowserConsole' config is true, it will
* write to the browser console if available. YUI-specific log
* messages will only be present in the -debug versions of the
* JS files. The build system is supposed to remove log statements
* from the raw and minified versions of the files.
*
* @method log
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.log = function(msg, cat, src, silent) {
var bail, excl, incl, m, f,
Y = INSTANCE,
c = Y.config,
publisher = (Y.fire) ? Y : YUI.Env.globalEvents;
// suppress log message if the config is off or the event stack
// or the event call stack contains a consumer of the yui:log event
if (c.debug) {
// apply source filters
if (src) {
excl = c.logExclude;
incl = c.logInclude;
if (incl && !(src in incl)) {
bail = 1;
} else if (incl && (src in incl)) {
bail = !incl[src];
} else if (excl && (src in excl)) {
bail = excl[src];
}
}
if (!bail) {
if (c.useBrowserConsole) {
m = (src) ? src + ': ' + msg : msg;
if (Y.Lang.isFunction(c.logFn)) {
c.logFn.call(Y, msg, cat, src);
} else if (typeof console != UNDEFINED && console.log) {
f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log';
console[f](m);
} else if (typeof opera != UNDEFINED) {
opera.postError(m);
}
}
if (publisher && !silent) {
if (publisher == Y && (!publisher.getEvent(LOGEVENT))) {
publisher.publish(LOGEVENT, {
broadcast: 2
});
}
publisher.fire(LOGEVENT, {
msg: msg,
cat: cat,
src: src
});
}
}
}
return Y;
};
/**
* Write a system message. This message will be preserved in the
* minified and raw versions of the YUI files, unlike log statements.
* @method message
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.message = function() {
return INSTANCE.log.apply(INSTANCE, arguments);
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('dump', function(Y) {
/**
* Returns a simple string representation of the object or array.
* Other types of objects will be returned unprocessed. Arrays
* are expected to be indexed. Use object notation for
* associative arrays.
*
* If included, the dump method is added to the YUI instance.
*
* @module dump
*/
var L = Y.Lang,
OBJ = '{...}',
FUN = 'f(){...}',
COMMA = ', ',
ARROW = ' => ',
/**
* Returns a simple string representation of the object or array.
* Other types of objects will be returned unprocessed. Arrays
* are expected to be indexed.
*
* @method dump
* @param {Object} o The object to dump.
* @param {Number} d How deep to recurse child objects, default 3.
* @return {String} the dump result.
* @for YUI
*/
dump = function(o, d) {
var i, len, s = [], type = L.type(o);
// Cast non-objects to string
// Skip dates because the std toString is what we want
// Skip HTMLElement-like objects because trying to dump
// an element will cause an unhandled exception in FF 2.x
if (!L.isObject(o)) {
return o + '';
} else if (type == 'date') {
return o;
} else if (o.nodeType && o.tagName) {
return o.tagName + '#' + o.id;
} else if (o.document && o.navigator) {
return 'window';
} else if (o.location && o.body) {
return 'document';
} else if (type == 'function') {
return FUN;
}
// dig into child objects the depth specifed. Default 3
d = (L.isNumber(d)) ? d : 3;
// arrays [1, 2, 3]
if (type == 'array') {
s.push('[');
for (i = 0, len = o.length; i < len; i = i + 1) {
if (L.isObject(o[i])) {
s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ);
} else {
s.push(o[i]);
}
s.push(COMMA);
}
if (s.length > 1) {
s.pop();
}
s.push(']');
// regexp /foo/
} else if (type == 'regexp') {
s.push(o.toString());
// objects {k1 => v1, k2 => v2}
} else {
s.push('{');
for (i in o) {
if (o.hasOwnProperty(i)) {
try {
s.push(i + ARROW);
if (L.isObject(o[i])) {
s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ);
} else {
s.push(o[i]);
}
s.push(COMMA);
} catch (e) {
s.push('Error: ' + e.message);
}
}
}
if (s.length > 1) {
s.pop();
}
s.push('}');
}
return s.join('');
};
Y.dump = dump;
L.dump = dump;
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('transition-timer', function(Y) {
/*
* The Transition Utility provides an API for creating advanced transitions.
* @module transition
*/
/*
* Provides the base Transition class, for animating numeric properties.
*
* @module transition
* @submodule transition-timer
*/
var Transition = Y.Transition;
Y.mix(Transition.prototype, {
_start: function() {
if (Transition.useNative) {
this._runNative();
} else {
this._runTimer();
}
},
_runTimer: function() {
var anim = this;
anim._initAttrs();
Transition._running[Y.stamp(anim)] = anim;
anim._startTime = new Date();
Transition._startTimer();
},
_endTimer: function() {
var anim = this;
delete Transition._running[Y.stamp(anim)];
anim._startTime = null;
},
_runFrame: function() {
var t = new Date() - this._startTime;
this._runAttrs(t);
},
_runAttrs: function(time) {
var anim = this,
node = anim._node,
config = anim._config,
uid = Y.stamp(node),
attrs = Transition._nodeAttrs[uid],
customAttr = Transition.behaviors,
done = false,
allDone = false,
data,
name,
attribute,
setter,
elapsed,
delay,
d,
t,
i;
for (name in attrs) {
if ((attribute = attrs[name]) && attribute.transition === anim) {
d = attribute.duration;
delay = attribute.delay;
elapsed = (time - delay) / 1000;
t = time;
data = {
type: 'propertyEnd',
propertyName: name,
config: config,
elapsedTime: elapsed
};
setter = (i in customAttr && 'set' in customAttr[i]) ?
customAttr[i].set : Transition.DEFAULT_SETTER;
done = (t >= d);
if (t > d) {
t = d;
}
if (!delay || time >= delay) {
setter(anim, name, attribute.from, attribute.to, t - delay, d - delay,
attribute.easing, attribute.unit);
if (done) {
delete attrs[name];
anim._count--;
if (config[name] && config[name].on && config[name].on.end) {
config[name].on.end.call(Y.one(node), data);
}
//node.fire('transition:propertyEnd', data);
if (!allDone && anim._count <= 0) {
allDone = true;
anim._end(elapsed);
anim._endTimer();
}
}
}
}
}
},
_initAttrs: function() {
var anim = this,
customAttr = Transition.behaviors,
uid = Y.stamp(anim._node),
attrs = Transition._nodeAttrs[uid],
attribute,
duration,
delay,
easing,
val,
name,
mTo,
mFrom,
unit, begin, end;
for (name in attrs) {
if ((attribute = attrs[name]) && attribute.transition === anim) {
duration = attribute.duration * 1000;
delay = attribute.delay * 1000;
easing = attribute.easing;
val = attribute.value;
// only allow supported properties
if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) {
begin = (name in customAttr && 'get' in customAttr[name]) ?
customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name);
mFrom = Transition.RE_UNITS.exec(begin);
mTo = Transition.RE_UNITS.exec(val);
begin = mFrom ? mFrom[1] : begin;
end = mTo ? mTo[1] : val;
unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units
if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) {
unit = Transition.DEFAULT_UNIT;
}
if (typeof easing === 'string') {
if (easing.indexOf('cubic-bezier') > -1) {
easing = easing.substring(13, easing.length - 1).split(',');
} else if (Transition.easings[easing]) {
easing = Transition.easings[easing];
}
}
attribute.from = Number(begin);
attribute.to = Number(end);
attribute.unit = unit;
attribute.easing = easing;
attribute.duration = duration + delay;
attribute.delay = delay;
} else {
delete attrs[name];
anim._count--;
}
}
}
},
destroy: function() {
this.detachAll();
this._node = null;
}
}, true);
Y.mix(Y.Transition, {
_runtimeAttrs: {},
/*
* Regex of properties that should use the default unit.
*
* @property RE_DEFAULT_UNIT
* @static
*/
RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i,
/*
* The default unit to use with properties that pass the RE_DEFAULT_UNIT test.
*
* @property DEFAULT_UNIT
* @static
*/
DEFAULT_UNIT: 'px',
/*
* Time in milliseconds passed to setInterval for frame processing
*
* @property intervalTime
* @default 20
* @static
*/
intervalTime: 20,
/*
* Bucket for custom getters and setters
*
* @property behaviors
* @static
*/
behaviors: {
left: {
get: function(anim, attr) {
return Y.DOM._getAttrOffset(anim._node, attr);
}
}
},
/*
* The default setter to use when setting object properties.
*
* @property DEFAULT_SETTER
* @static
*/
DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) {
from = Number(from);
to = Number(to);
var node = anim._node,
val = Transition.cubicBezier(fn, elapsed / duration);
val = from + val[0] * (to - from);
if (node) {
if (att in node.style || att in Y.DOM.CUSTOM_STYLES) {
unit = unit || '';
Y.DOM.setStyle(node, att, val + unit);
}
} else {
anim._end();
}
},
/*
* The default getter to use when getting object properties.
*
* @property DEFAULT_GETTER
* @static
*/
DEFAULT_GETTER: function(anim, att) {
var node = anim._node,
val = '';
if (att in node.style || att in Y.DOM.CUSTOM_STYLES) {
val = Y.DOM.getComputedStyle(node, att);
}
return val;
},
_startTimer: function() {
if (!Transition._timer) {
Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime);
}
},
_stopTimer: function() {
clearInterval(Transition._timer);
Transition._timer = null;
},
/*
* Called per Interval to handle each animation frame.
* @method _runFrame
* @private
* @static
*/
_runFrame: function() {
var done = true,
anim;
for (anim in Transition._running) {
if (Transition._running[anim]._runFrame) {
done = false;
Transition._running[anim]._runFrame();
}
}
if (done) {
Transition._stopTimer();
}
},
cubicBezier: function(p, t) {
var x0 = 0,
y0 = 0,
x1 = p[0],
y1 = p[1],
x2 = p[2],
y2 = p[3],
x3 = 1,
y3 = 0,
A = x3 - 3 * x2 + 3 * x1 - x0,
B = 3 * x2 - 6 * x1 + 3 * x0,
C = 3 * x1 - 3 * x0,
D = x0,
E = y3 - 3 * y2 + 3 * y1 - y0,
F = 3 * y2 - 6 * y1 + 3 * y0,
G = 3 * y1 - 3 * y0,
H = y0,
x = (((A*t) + B)*t + C)*t + D,
y = (((E*t) + F)*t + G)*t + H;
return [x, y];
},
easings: {
ease: [0.25, 0, 1, 0.25],
linear: [0, 0, 1, 1],
'ease-in': [0.42, 0, 1, 1],
'ease-out': [0, 0, 0.58, 1],
'ease-in-out': [0.42, 0, 0.58, 1]
},
_running: {},
_timer: null,
RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/
}, true);
Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left;
Y.Transition = Transition;
}, '@VERSION@' ,{requires:['transition']});
YUI.add('simpleyui', function(Y) {
// empty
}, '@VERSION@' ,{use:['yui','oop','dom','event-custom-base','event-base','pluginhost','node','event-delegate','io-base','json-parse','transition','selector-css3','dom-style-ie','querystring-stringify-simple']});
var Y = YUI().use('*');
|